You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
That is, I would like to verify that two mocked methods are called the same unspecified number of times. The number of calls made to a method appears to be already available, so this would be just querying the value directly, not indirectly via times(), atLeast(), etc.
I also posed this question to StackOverflow, and one answer, on using an Answer, seems good; perhaps a standard Answer implementation CountsCalls or similar should be the solution?
The text was updated successfully, but these errors were encountered:
In order to count the number of invocations,
InvocationsCounter can keep track of the number of invocations
using an AtomicInteger.
This AtomicInteger can then be used in Mockito.times(AtomicInteger)
or with Assert.assertEquals(int, int) in order to verify behaviour.
You can use a custom VerificationMode to count the invocations, here you go:
public class InvocationCounter {
public static <T> T countInvocations(T mock, AtomicInteger count) {
return Mockito.verify(mock, new Counter(count));
}
private InvocationCounter(){}
private static class Counter implements VerificationInOrderMode, VerificationMode {
private final AtomicInteger count;
private Counter(AtomicInteger count) {
this.count = count;
}
public void verify(VerificationData data) {
count.set(data.getAllInvocations().size());
}
public void verifyInOrder(VerificationDataInOrder data) {
count.set(data.getAllInvocations().size());
}
@Override
public VerificationMode description(String description) {
return VerificationModeFactory.description(this, description);
}
}
}
And then use it like this (works also with void return types):
@Mock
private Function<String, Integer> callable;
AtomicInteger count= new AtomicInteger(); //here is the actual invocation count stored
countInvocations(callable,count).apply( anyString());
assertThat(count.get(),is(2));
We can do this:
But we cannot do something like this, as far as I can see:
That is, I would like to verify that two mocked methods are called the same unspecified number of times. The number of calls made to a method appears to be already available, so this would be just querying the value directly, not indirectly via
times()
,atLeast()
, etc.I also posed this question to StackOverflow, and one answer, on using an
Answer
, seems good; perhaps a standardAnswer
implementationCountsCalls
or similar should be the solution?The text was updated successfully, but these errors were encountered: