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. 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 {
// ...
}
}
It can also be an import problem, so make sure you have the appropriate imported package.
For example, the "org.easymock" package also does have an annotation called @Mock, which of course, won't work with Mockito specific setup.
Try to to check if the method that you are calling is a final method or not.
Mockito cannot mock the final method. https://github.com/mockito/mockito/wiki/FAQ
If you are also using PowerMock then
@RunWith(MockitoJUnitRunner.class)
can be replaced with
@RunWith(PowerMockRunner.class)
This will activate your @Mocks
and enable the PowerMock functionality.