Reputation: 207
I am using Spock to verify that a method has been called once for each of a set of values:
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)
}
This performs the necessary verifications, but if there's a failure I get an unhelpful error message:
Too few invocations for:
1 * foo.something(it) (0 invocations)
Is there some way of generating a custom error message here, so that (for example) the following will be shown instead:
Too few invocations for:
1 * foo.something(3) (0 invocations)
I tried using an assert
:
assert (1 * foo.something(it)) : "No something for ${it}"
but got a compiler error.
edit: changed new Foo()
to Mock(Foo)
Upvotes: 2
Views: 1575
Reputation: 123950
You'll need to check the validity of arguments using assertions. For example, if it's tolerable/desirable to check the order of calls, you can do:
...
then:
(1..100).each { n ->
1 * foo.something(_) >> { int arg -> assert arg == n }
}
Upvotes: 1