How can I verify that a method is called exactly two times using Mockito’s verify()?

I’m working with Mockito and need to check if a specific method is invoked twice during a test. When I use a basic verify() call, I get an error like this:

org.mockito.exceptions.verification.TooManyActualInvocations:
Wanted 1 time:
But was 2 times. Undesired invocation:

What’s the correct way to use Mockito.verify() with times() to confirm that a method has been called two times?

Also, is there a way to check for “at least” or “at most” invocations instead of an exact number?

Any clear example or explanation on how to use mockito times properly would be helpful.

If you want to verify that a method was called exactly two times, use times(2) with verify():

verify(mockObject, times(2)).someMethod();

This ensures Mockito expects exactly two invocations of someMethod() on the mock.

If it’s called more or less, the test fails.

Mockito also allows flexible verification using:


verify(mockObject, atLeast(2)).someMethod(); // at least twice
verify(mockObject, atMost(2)).someMethod();  // at most twice

Use these when the number of calls can vary, but you still want to enforce a lower or upper limit.

You can combine times() with verifyNoMoreInteractions() to ensure no unexpected calls happened:

verify(mockObject, times(2)).someMethod();
verifyNoMoreInteractions(mockObject);

This confirms the method was called exactly twice, and nothing else was invoked on the mock.