gpt4 book ai didi

where-clause - 如何在 spock 测试的 where 子句中调用方法或闭包

转载 作者:行者123 更新时间:2023-12-04 17:35:29 24 4
gpt4 key购买 nike

我正在使用 Spock 测试 atm,我想知道这样的事情是否可行。我的方法不起作用,我想知道你们中是否有人有类似的意图并找到了方法。

我想调用一个方法或一个闭包,必须只为每个各自的 where 子句调用它,以便设置一些东西。我不能只调用所有这些方法,因为它会破坏我的测试。到目前为止,我发现的唯一方法是检查当前状态并在 if 语句中相应地调用该方法,例如: if(state==SomeStateEnum.FIRST_STATE){somePrivateMethodFromSpec()} 但我想知道它是否无法完成以更好的方式。我希望我的意图很明确(对不起,我不是母语人士)下面是一些示例代码,可能会更好地理解我想要做什么。先感谢您。

def 'is this even possible?'() {
when:
def resultState = service.someServiceMethod(param)

then:
resultState == state

where:
state | param | method
SomeStateEnum.FIRST_STATE | 'param1' | somePrivateMethodFromSpec()
SomeStateEnum.SECOND_STATE | 'param2' | someOtherPrivateMethodFromSpec()
}

private def somePrivateMethodFromSpec() {
someServiceMock.demand.AAA() {}
}

private def someOtherPrivateMethodFromSpec() {
someServiceMock.demand.BBB() {}
}

def 'or maybe something like this?'() {
when:
closure.call()
def resultState = service.someServiceMethod(param)

then:
resultState == state

where:
state | param | closure
SomeStateEnum.FIRST_STATE | 'param1' | {println '1'}
SomeStateEnum.SECOND_STATE | 'param2' | {println '2'}
}

解决办法是:
def 'this will work'() {
"$someOtherPrivateMethodFromSpec"()
"$somePrivateMethodFromSpec"()
def resultState = service.someServiceMethod(param)

then:
resultState == state

where:
state | param | method
SomeStateEnum.FIRST_STATE | 'param1' | "somePrivateMethodFromSpec"
SomeStateEnum.SECOND_STATE | 'param2' | "someOtherPrivateMethodFromSpec"
}

private def somePrivateMethodFromSpec() {
someServiceMock.demand.AAA() {}
}

private def someOtherPrivateMethodFromSpec() {
someServiceMock.demand.BBB() {}
}

最佳答案

为了调用闭包方式,您只需要在 where 子句中的闭包周围添加更多括号。

例如。 ({ println("1") })

或者作为完整的规范。

def 'or maybe something like this?'() {
when:
closure.call()
def resultState = service.someServiceMethod(param)

then:
resultState == state

where:
state | param | closure
SomeStateEnum.FIRST_STATE | 'param1' | ({println '1'})
SomeStateEnum.SECOND_STATE | 'param2' | ({println '2'})
}

关于where-clause - 如何在 spock 测试的 where 子句中调用方法或闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113794/

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