无法使用 PowerMock 模拟 httpClient.execute 方法

unable to mock httpClient.execute method using PowerMock

我正在使用 EasyMock 和 PowerMock 来模拟外部 WS 调用。我可以模拟 getHttpClient 方法,它是一个私有方法和 returns CloseableHttpClient 但我无法模拟 httpClient.execute(httpPost) 调用。我在 httpResponse 中得到 null,因为我期望 200 http 状态代码。

public class MyWsClient {

public void post(String data) throws Exception {

    CloseableHttpResponse httpResponse = null;
    String url = "http://abc:8080/myapp/mysvc"
    ...
    ....

    try {
        CloseableHttpClient httpClient = getHttpClient();

         HttpPost httpPost = new HttpPost(url);
        //populate the headers
        ....
        //set entity logic goes heres
        ....
        ......
        httpResponse = httpClient.execute(httpPost);


    } catch (Exception e) {
        //exception handling
    }   
  }
}

测试用例:

@Test
public void testPostWs() {
    try {
        // Given            
        CloseableHttpClient mockHttpClient = EasyMock.createMock(CloseableHttpClient.class);
        CloseableHttpResponse mockResponse = EasyMock.createMock(CloseableHttpResponse.class);
        MyWsClient classUnderTest = PowerMock.createPartialMock(MyWsClient.class, "getHttpClient");

        EasyMock.expect(mockResponse.getStatusLine()).andReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "CREATED!"));


        PowerMock.expectPrivate(classUnderTest, "getHttpClient").andReturn(mockHttpClient);

        EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost.class))).andReturn(mockResponse);
        PowerMock.replayAll(classUnderTest);
        //when
        classUnderTest.post(data);
    }  catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}   

您需要在最后执行 Easymock.replay(mockHttpClient,mockResponse) 以便激活模拟。