是否有可能在Spock中获取模拟方法的调用次数?我想测试方法是否被调用特定次数,但每秒返回的值应该是不同的。下面的伪代码应该更具体地说明我想要的内容:
void "My idea of a test" {
when:
...
then:
10 * someService(_) >> {
return theNumberOfTheCall % 2 ? SOME_VALUE : null // theNumberOfTheCall should illustrate my purpose
}
// so the service will return [null, SOME_VALUE, null, SOME_VALUE, null ...]
}
答案 0 :(得分:3)
可以使用链接来完成:
10 * someService(_) >>> (1..10).collect {
it % 2 ? SOME_VALUE : null
}
答案 1 :(得分:1)
Spock本身并没有将一些调用传递给mocked方法,但是你使用AtomicInteger
来增加测试方法中定义的计数器。请考虑以下简单示例:
import spock.lang.Specification
import java.util.concurrent.atomic.AtomicInteger
class InvocationCounterSpec extends Specification {
def "should return different value depending on invocation counter"() {
setup:
final AtomicInteger counter = new AtomicInteger(0)
final SomeService someService = Mock(SomeService)
final SomeClass someClass = new SomeClass(someService)
when:
someClass.run()
then:
10 * someService.someMethod() >> {
return counter.getAndIncrement() % 2 ? "SOME_VALUE" : null
}
}
static interface SomeService {
def someMethod()
}
static class SomeClass {
private final SomeService someService
SomeClass(SomeService someService) {
this.someService = someService
}
void run() {
(0..<10).each {
def value = someService.someMethod()
println "someService.someMethod() returned ${value}"
}
}
}
}
在此示例中,someClass.run()
方法调用模拟someService.someMethod()
10次。我们使用计算我们的调用号的计数器来存储someService.someMethod()
返回的值。如果您运行此测试,您将看到以下输出:
someService.someMethod() returned null
someService.someMethod() returned SOME_VALUE
someService.someMethod() returned null
someService.someMethod() returned SOME_VALUE
someService.someMethod() returned null
someService.someMethod() returned SOME_VALUE
someService.someMethod() returned null
someService.someMethod() returned SOME_VALUE
someService.someMethod() returned null
someService.someMethod() returned SOME_VALUE
希望它有所帮助。