模拟实例在@Mock 注释后为空

2022-01-08 00:00:00 mocking unit-testing mockito java junit

我尝试运行这个测试:

    @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);

...
    }

但我得到 NullPointerException:

but I get NullPointerException for:

Mockito.when(routingClientMock.

我错过了什么?

推荐答案

当你想使用 @Mock 注解时你应该使用 MockitoJUnitRunner

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 {
        // ...
    }

}

另请参阅本教程.

相关文章