How can I verify if a method is called exactly two times using Mockito’s verify()?
I want to check if a method is called exactly two times, but when I use verify(), I encounter the following error:
org.mockito.exceptions.verification.TooManyActualInvocations: Wanted 1 time: But was 2 times. Undesired invocation:
I am looking to use mockito verify times to achieve this.
Using times() Verification Mode: This is the most direct way to verify that a method was called exactly a specific number of times. The times(2) mode ensures that the method someMethod was invoked exactly two times. If the method is called more or fewer times, Mockito will throw an assertion error.
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
// Verify that someMethod was called exactly two times
verify(mockObject, times(2)).someMethod(“expected arguments”);
I often like to use verifyNoMoreInteractions() right after counting method calls to keep things tidy. Here’s how I typically do it:
verify(mockObject, times(2)).someMethod("expected arguments");
verifyNoMoreInteractions(mockObject);
First, the verify(mockObject, times(2)).someMethod("expected arguments");
checks that the method was called exactly two times, which gives me confidence that my logic is working as intended.
Then, by adding verifyNoMoreInteractions(mockObject);
, I make sure that no extra, unintended calls were made on mockObject
. It’s a simple, effective way to confirm everything is running smoothly without any sneaky extra calls. This little routine has helped me catch subtle issues more than once!
Combining times() with verify() in a Custom Method:
public void verifyMethodCalledExactlyTwice(MyClass mockObject) {
verify(mockObject, times(2)).someMethod("expected arguments");
}
This method encapsulates the verification logic within a custom method for reusability. It verifies that someMethod was called exactly twice on mockObject. This approach is useful for organizing tests and keeping the verification logic clean and reusable.