【发布时间】:2015-11-02 08:22:34
【问题描述】:
如何在 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)
}
【问题讨论】: