如何在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)
}
答案 0 :(得分:1)
你可以这样写:
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