我正在使用Spock验证是否已为每组值调用一次方法:
def "something happens a lot"() {
given:
def foo = Mock(Foo)
when: "call something one hundred times"
doSomethingThisManyTimes(foo, 100)
then: "verify something was invoked one hundred times, with correct argument"
(1..100).each { 1 * foo.something(it) }
}
private void doSomethingThisManyTimes(object,n) {
(1..n).eachWithIndex { it, i ->
// Skip the third value
if (i != 3) {
object.something(it) }
}
}
interface Foo {
void something(int n)
}
这会执行必要的验证,但如果出现故障,我会收到无用的错误消息:
Too few invocations for:
1 * foo.something(it) (0 invocations)
是否有某种方法可以在此处生成自定义错误消息,以便(例如)显示以下内容:
Too few invocations for:
1 * foo.something(3) (0 invocations)
我尝试使用assert
:
assert (1 * foo.something(it)) : "No something for ${it}"
但是编译错误。
修改:将new Foo()
更改为Mock(Foo)
答案 0 :(得分:1)
您需要使用断言检查参数的有效性。例如,如果检查呼叫顺序是可以容忍的/可取的,您可以这样做:
...
then:
(1..100).each { n ->
1 * foo.something(_) >> { int arg -> assert arg == n }
}