While using mockito for unit test, you initialize using either
@RunWith(MockitoJUnitRunner.class)
or
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
If you are getting NPE for the mocked objects at the class you are testing, then you have missed either of the above. MockitoJUnitRunner automatically provides you with a initMocks() It also provides automatic validation of framework usage.
There might be cases where you are already using runner, say, SpringJunit4ClassRunner. In such cases you cannot have 2 runners. In such scenarios, we can go with
- the second approach using initMocks.
- With JUnit 4.12, we can have multiple runners operate on the same test class by means of JUnit Rules. Mockito already provides us MockitoRule
Note that when you are trying to write Parameterized tests, always use runner for Parameterized and rule for Mockito. Quoting this reference
@RunWith(MockitoJUnitRunner.class)
or
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
If you are getting NPE for the mocked objects at the class you are testing, then you have missed either of the above. MockitoJUnitRunner automatically provides you with a initMocks() It also provides automatic validation of framework usage.
There might be cases where you are already using runner, say, SpringJunit4ClassRunner. In such cases you cannot have 2 runners. In such scenarios, we can go with
- the second approach using initMocks.
- With JUnit 4.12, we can have multiple runners operate on the same test class by means of JUnit Rules. Mockito already provides us MockitoRule
Note that when you are trying to write Parameterized tests, always use runner for Parameterized and rule for Mockito. Quoting this reference
The reason is that the Runner is responsible for reporting the number of tests, and Parameterized manipulates the number of tests based on the number of test methods and the number of parameterized inputs, so it's really important for Parameterized to be a part of the Runner process. By contrast, the use of a Mockito runner or rule is simply to encapsulate the @Before and @After methods that initialize Mockito annotations and validate Mockito usage, which can be done very easily as a @Rule that works adjacent to other @Rule instances--to the point that the MockitoJUnitRunner is very nearly deprecated.