First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
http://code.google.com/p/mockito/wiki/FAQ
In case of questions you may also post to mockito mailing list: http://groups.google.com/group/mockito
validateMockitoUsage()
explicitly validates the framework state to detect invalid use of Mockito.
However, this feature is optional because Mockito validates the usage all the time... but there is a gotcha so read on.
Examples of incorrect use:
//Oups, someone forgot thenReturn() part:
when(mock.get());
//Oups, someone put the verified method call inside verify() where it should be outside:
verify(mock.execute());
//Oups, someone has used EasyMock for too long and forgot to specify the method to verify:
verify(mock);
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.
Built-in runner:
MockitoJUnitRunner does validateMockitoUsage() after each test method.
Bear in mind that usually you don't have to validateMockitoUsage()
and framework validation triggered on next-time basis should be just enough,
mainly because of enhanced exception message with clickable location of defect.
However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure
(like your own runner or base class for all tests) because adding a special action to @After
has zero cost.
See examples in javadoc for
Mockito class