mock instance is null after @Mock annotation
I try to run this test:
@Mock IRoutingObjHttpClient routingClientMock;
@Mock IRoutingResponseRepository routingResponseRepositoryMock;
@Test
public void testSendRoutingRequest() throws Exception {
CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse();
completeRoutingResponse.regression_latencyMillis = 500L;
Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse);
RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun
(routingClientMock, routingResponseRepositoryMock);
...
}
but I get NullPointerException for:
Mockito.when(routingClientMock.
what am i missing?
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.
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 {
// ...
}
}