When using MockFor, how can I get it to verify that a method was invoked at least n times? I’ve tried ignoring the method call after setting up a demand, like this:
import groovy.mock.interceptor.MockFor;
import org.junit.Test
class FilterTest {
interface Filter {
boolean isEnabled()
}
@Test
public void test() {
MockFor mockContext = new MockFor(Filter)
// Expect at least one call
mockContext.demand.isEnabled {true}
mockContext.ignore.isEnabled {false}
// Obtaining a usuable mock instance
def filter = mockContext.proxyInstance()
// Fake calling the method
filter.isEnabled()
filter.isEnabled()
// Verify invoked at least once?
mockContext.verify(filter)
}
}
However, I get an assertion failure:
junit.framework.AssertionFailedError: verify[0]: expected 1..1 call(s) to
'isEnabled' but was called 0 time(s).
You can’t combine “demand” and “ignore” in that way, since the “ignore” statement overrides the “demand” statement.
Instead, you can specify the valid range like this:
which will accept 1 to 10 number of invokations (but not zero or eleven or more).
I’m not aware of any way to specify an open ended upper bound in ranges, though, which you imply that you need when you say “at least n times”.
In most practical situations, I believe you can get away with specifying a sufficiently large upper bound (like 100).
EDIT: Removed the “hack” suggestion (it didn’t work as I expected)