Java , PowerMock -- 基于 HttpPost 请求体的 Mock Response

Java , PowerMock -- Mock Response based on HttpPost request body

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

现在使用这种测试方法,我可以只模拟对 POST 调用 url 的一个响应。 是否可以根据 POST 请求主体(即基于请求实体)模拟多个响应?

您或许可以使用 ArgumentCaptor 和答案:

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";
            }
        }
    });