gpt4 book ai didi

Java、PowerMock——基于HttpPost请求体的模拟响应

转载 作者:行者123 更新时间:2023-12-02 09:16:14 25 4
gpt4 key购买 nike

我有多个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com