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

问题描述 投票:0回答:1

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

java http mockito http-post powermock
1个回答
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";
            }
        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.