【发布时间】: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 不正确?
【问题讨论】:
-
您需要初始化 Mockito 以便
res实际上设置为 Mock。见stackoverflow.com/questions/40961057/…
标签: java testing mocking mockito httpclient