我有多个 HttpPost 请求,如下所示:
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(searchURL);
httpPost.setEntity(...);
ResponseHandler<String> responseHandler = response -> {
HttpEntity httpEntity = response.getEntity();
return httpEntity != null ? EntityUtils.toString(httpEntity) : null;
};
String responseBody = httpclient.execute(httpPost, responseHandler);
} catch()...
为了测试这些类,我模拟了 HttpPost 请求,如下所示:
when(HttpClients.createDefault()).thenReturn(client);
when(response.getEntity()).thenReturn(entity);
whenNew(HttpPost.class).withArguments(url).thenReturn(httpPostSearchOrg);
when(client.execute(same(httpPostSearchOrg), any(ResponseHandler.class)))
.thenReturn(JSON_STRING);
现在,通过这种测试方法,我只能模拟对 URL 的 POST 调用的一个响应。 是否可以基于 POST 请求正文(即基于请求实体)模拟多个响应?
最佳答案
您可以使用 ArgumentCaptor 和 Answer:
ArgumentCaptor<HttpEntity> requestEntity = ArgumentCaptor.forClass(HttpEntity.class);
Mockito.doNothing().when(httpPostSearchOrg).setEntity(requestEntity.capture());
when(client.execute(same(httpPostSearchOrg), any(ResponseHandler.class))).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (matchesEntityToReturnResponse1(requestEntity.getValue())) {
return "RESPONSE1";
} else {
return "RESPONSE2";
}
}
});
关于Java、PowerMock——基于HttpPost请求体的模拟响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58959112/