gpt4 book ai didi

groovy - 模拟中的 spock 可重复使用闭包

转载 作者:行者123 更新时间:2023-12-02 03:20:57 25 4
gpt4 key购买 nike

如何在 spock 模拟中重用闭包?

我可以在运行时键入闭包 (mock.sth({closure}) 但我如何创建命名的 clsoure 以供重用或提高代码可读性 (mock.sth(hasStuffAsExpected))?

我有课:

class Link {
String url
boolean openInNewWindow
}

现在有服务

interface LinkService {
boolean checkStuff(Link link)
}

在我的测试中,我想创建这样的东西:

@Shared def linkIsOpenInNewWindow = { Link l -> l.isOpenInNewWindow }
@Shared Closure linkIsHttps = { Link l -> l.url.startsWith("https") }

expect:
1 * linkService.checkStuff(linkIsHttps) >> true
1 * linkService.checkStuff(linkIsOpenInNewWindow) >> false

当我运行这段代码时,它总是:

Too few invocations for:

1 * linkService.checkStuff(linkIsHttps) >> true (0 invocations)

Unmatched invocations (ordered by similarity):

1 * linkService.checkStuff(Link@1234)

有什么方法可以实现这一点并在 spock 中创建和使用命名的可重用闭包吗?

伪规范:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4')
@Grab('cglib:cglib:3.1')
@Grab('org.ow2.asm:asm-all:5.0.3')

import spock.lang.Shared
import spock.lang.Specification

class Test extends Specification {

LinkService linkService = Mock(LinkService)

@Shared
Closure openInNewWindow = { it.isOpenInNewWindw()}

@Shared
def httpsLink = { Link l -> l.url.startsWith("https") }

@Shared
def secureLink = new Link(
url: "https://exmaple.com",
openInNewWindw: false
)

@Shared
def externalLink = new Link(
url: "http://exmaple.com",
openInNewWindw: true
)

def "failing closure test"() {
when:
def secureLinkResult = linkService.doStuff(secureLink)
def externalLinkResult = linkService.doStuff(externalLink)

then:
secureLinkResult == 1
externalLinkResult == 2

1 * linkService.doStuff(httpsLink) >> 1
1 * linkService.doStuff(openInNewWindow) >> 2
}

def "passing closure test"() {
when:
def secureLinkResult = linkService.doStuff(secureLink)
def externalLinkResult = linkService.doStuff(externalLink)

then:
secureLinkResult == 1
externalLinkResult == 2

1 * linkService.doStuff({Link l -> l.url.startsWith("https")}) >> 1
1 * linkService.doStuff({Link l -> l.openInNewWindw}) >> 2
}
}

class Link {
String url
boolean openInNewWindw
}

interface LinkService {
int doStuff(Link link)
}

最佳答案

你可以这样写:

def "failing closure test"() {
when:
def secureLinkResult = linkService.doStuff(secureLink)
def externalLinkResult = linkService.doStuff(externalLink)

then:
secureLinkResult == 1
externalLinkResult == 2

1 * linkService.doStuff({ httpsLink(it) }) >> 1
1 * linkService.doStuff({ openInNewWindow(it) }) >> 2
}

可以找到一些解释in this thread

关于groovy - 模拟中的 spock 可重复使用闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33473363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com