mock instance is null after @Mock annotation
You have three options for activating the @Mock
annotation: MockitoRule, MockitoJUnitRunner, MockitoAnnotations.initMocks(this). IMHO using the MockitoRule
is the best one, because it lets you still choose another runner like e.g. Parameterized
.
Use the MockitoRule
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Use the MockitoJUnitRunner
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
Call MockitoAnnotations.initMocks(this) explicitly.
This can be done in qn @Before
method, in your own runner or in an own rule.
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Before
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
When you want to use the @Mock
annotation you should use the MockitoJUnitRunner
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock
private IRoutingObjHttpClient routingClientMock;
@Test
public void testSendRoutingRequest() throws Exception {
// ...
}
}
See also this tutorial.
Same problem can occur if you are using Junit5 since there is no more '@RunWith' annotation.
In this case you should annotate your class with:
@ExtendWith(MockitoExtension.class)
public class MyTestClass {
...
You should also import into your dependency (Maven - pom.xml):
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>