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

标签 java http mockito http-post powermock

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

相关文章:

java - 使用 POI 删除 excel 中的一行

c# - 如何向网络服务发送特殊字符?

java - 在 SQL 语句中调用具有默认值的函数

C++ 从 HTTP 响应中获取图片

java - 在一个类中模拟两个 map

java - 将值动态附加到 long[] 数组中

javascript - Angular 服务调用 API 导致 switchmap 错误

带有 header() 和 Bad header 问题的 PHP POST

scala - scala : Mockito 中的模拟案例类

unit-testing - Junit5模拟静态方法