【问题标题】:Java , PowerMock -- Mock Response based on HttpPost request bodyJava , PowerMock -- 基于 HttpPost 请求体的模拟响应
【发布时间】:2019-11-20 16:29:57
【问题描述】:

我有多个 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 请求正文(即基于请求实体)模拟多个响应?

【问题讨论】:

    标签: java http mockito http-post powermock


    【解决方案1】:

    您可能可以使用 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";
                }
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      相关资源
      最近更新 更多