Mockito gives UnfinishedVerificationException when it seems OK

This might also be caused if you try to verify a method which expects primitive arguments with any():

For example, if our method has this signature:

method(long l, String s);

And you try to verify it like this, it will fail with aforementioned message:

verify(service).method(any(), anyString());

Change it to anyLong() and it will work:

verify(service).method(anyLong(), anyString());

I was getting this same error due to using any() with a boolean parameter, when apparently it needed to be anyBoolean().


I just came across this my self and it caused me a lot of confusion.

As David mentioned above Mockito reports errors in the next Mockito method call which may not be in the same test method. While the exception message does contain a reference to the actual place the error occurred I find having incorrect tests failing counter productive to the testing process. And the simpler the tests the more likely an error is to show up in the next test!

Here is an easy fix that will ensure errors appear in the correct test method:

@After
public void validate() {
    validateMockitoUsage();
}

From the Mockito documentation here:

Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. The gotcha is that Mockito does the validation next time you use the framework (e.g. next time you verify, stub, call mock etc.). But even though the exception might be thrown in the next test, the exception message contains a navigable stack trace element with location of the defect. Hence you can click and find the place where Mockito was misused.

Sometimes though, you might want to validate the framework usage explicitly. For example, one of the users wanted to put validateMockitoUsage() in his @After method so that he knows immediately when he misused Mockito. Without it, he would have known about it not sooner than next time he used the framework. One more benefit of having validateMockitoUsage() in @After is that jUnit runner will always fail in the test method with defect whereas ordinary 'next-time' validation might fail the next test method. But even though JUnit might report next test as red, don't worry about it and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.