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

Java、PowerMock——基于HttpPost请求体的模拟响应,java,http,mockito,http-post,powermock,Java,Http,Mockito,Http Post,Powermock,我有多个HttpPost请求,如下所示: try (CloseableHttpClient httpclient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(searchURL); httpPost.setEntity(...); ResponseHandler<String> responseHandler = response -> { HttpE

我有多个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()...
现在,使用这种测试方法,我只能模拟对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";
            }
        }
    });
ArgumentCaptor requestEntity=ArgumentCaptor.forClass(HttpEntity.class);
Mockito.doNothing().when(httpPostSearchOrg.setEntity)(requestEntity.capture());
when(client.execute(same(httpPostSearchOrg)、any(ResponseHandler.class)).thenAnswer(new-Answer(){
@凌驾
公共对象应答(InvocationMock调用)抛出Throwable{
if(matchesEntityToReturnResponse1(requestEntity.getValue())){
返回“RESPONSE1”;
}否则{
返回“RESPONSE2”;
}
}
});
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";
            }
        }
    });