【问题标题】:Mockito -- Response from service returns null in test - JavaMockito - 来自服务的响应在测试中返回 null - Java
【发布时间】:2022-07-06 13:17:58
【问题描述】:

我正在测试一个类。这个类调用一个服务(假设它叫client,我们想叫client.put()

put() 应该返回一个响应,但至少在测试中,响应是 null

我不知道我是否只是没有正确设置模拟并想在这里与你们进行理智检查

public class ATest {
    @Mock
    private ServiceProto.PutItemsResponse res;
    ...(private variables)...
    @Before
    public void setUp() throws Exception {
        client = mock(Client.class);
        clientFactory = mock(ClientFactory.class);
        when(clientFactory.get(any())).thenReturn(client);
        ...(initializing private vars for constructor as mock variables, example below...)
        captionConverter = mock(CaptionToCTItemConverter.class);
       when(privateVar.convert(any(obj.class))).thenReturn(Item.newBuilder().build());
     
        classAToTest = spy(new ClassAToTest(private variables);
    }
    @Test
    public void putItem() {
        long id = 4710582L;
        AObject aObject = testUtils.getObject();
        doReturn(res).when(client).putItems(any(ServiceProto.PutItemsRequest.class));
        System.out.println("result is "+ res);
        try {
             classAToTest.putMethod(aObject);
        }
        catch (NullPointerException e) {
        }
        verify(creativeToolsClient, Mockito.times(1)).putItems(any(IngestionServiceProto.PutItemsRequest.class));
    }

}

这是正在测试的方法

public void putMethod(AObject aObject) {
    final String id = Long.toString(aObject.getId());
    ServiceProto.PutItemsResponse putItemsResponse = null;
    Exception putItemsFailure = null;
    putItemsResponse =
            client.putItems(ServiceProto.PutItemsRequest.newBuilder()
                    .putItems(
                            id,
                            ServiceProto.PutItemsRequest.Item.newBuilder()).build())
                    .build());

    if (putItemsResponse == null) {
        logger.warning("PutItems request has failed: "+
                (putItemsFailure == null ? "null" : putItemsFailure.getMessage()));
    }
}

当我运行它时它会发出警告

putItems 方法适用于其他人。是不是我设置的 mock 不正确?

【问题讨论】:

标签: java testing mocking mockito httpclient


【解决方案1】:

res 变量未初始化。要使用 @Mock 注释模拟对象,请使用

@ExtendWith(MockitoExtension.class)
public class ATest {
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多