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

spock reusable closure in mocks

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

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

我有 class:

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