MockitoJUnitRunner
gives you automatic validation of framework usage, as well as an automatic initMocks()
.
The automatic validation of framework usage is actually worth having. It gives you better reporting if you make one of these mistakes.
You call the static when
method, but don't complete the stubbing with a matching thenReturn
, thenThrow
or then
. (Error 1 in the code below)
You call verify
on a mock, but forget to provide the method call
that you are trying to verify. (Error 2 in the code below)
You call the when
method after doReturn
, doThrow
or
doAnswer
and pass a mock, but forget to provide the method that
you are trying to stub. (Error 3 in the code below)
If you don't have validation of framework usage, these mistakes are not reported until the following call to a Mockito method. This might be
- in the same test method (like error 1 below),
- in the next test method (like error 2 below),
- in the next test class.
If they occur in the last test that you run (like error 3 below), they won't be reported at all.
Here's how each of those types of errors might look. Assume here that JUnit runs these tests in the order they're listed here.
@Test
public void test1() {
when(myMock.method1());
doSomeTestingStuff();
verify(myMock).method2();
}
@Test
public void test2() {
doSomeTestingStuff();
verify(myMock);
}
@Test
public void test3() {
doReturn("Hello").when(myMock).method1();
doReturn("World").when(myMock);
doSomeTestingStuff();
}
Now when I first wrote this answer more than five years ago, I wrote
So I would recommend the use of the MockitoJUnitRunner
wherever possible. However, as Tomasz Nurkiewicz has correctly pointed out, you can't use it if you need another JUnit runner, such as the Spring one.
My recommendation has now changed. The Mockito team have added a new feature since I first wrote this answer. It's a JUnit rule, which performs exactly the same function as the MockitoJUnitRunner
. But it's better, because it doesn't preclude the use of other runners.
Include
@Rule
public MockitoRule rule = MockitoJUnit.rule();
in your test class. This initialises the mocks, and automates the framework validation; just like MockitoJUnitRunner
does. But now, you can use SpringJUnit4ClassRunner
or any other JUnitRunner as well. From Mockito 2.1.0 onwards, there are additional options that control exactly what kind of problems get reported.