nbpeth nbpeth - 5 months ago 172
Java Question

Java verify void method calls n times with Mockito

I'm trying to verify that a (void) method is being called inside of a DAO - I'm using a commit point that sends a list of results up to that point, resets the list and continues.
Say I have 4 things in the list and I have a commit point of 1, I would expect the "send" method to be called 4 times.
I can verify that the method gets called once by writing


it passes.. but I want to verify the number of times it was called. I would think that

Mockito.verify(mock.send(), times(4))

would be sufficient, but it says the parameters are not correct for verify.

Incidentally, if I change
I get the same error. Thoughts on this?

Tom Tom

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerifactionMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock).someMethod("was ");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

(The class VerificationModeFactory also provides the mentioned verification modes. So you could also use this class for the static imports.)

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.