【问题标题】:unable to mock httpClient.execute method using PowerMock无法使用 PowerMock 模拟 httpClient.execute 方法
【发布时间】:2015-01-28 16:37:40
【问题描述】:

我正在使用 EasyMock 和 PowerMock 来模拟外部 WS 调用。我可以模拟作为私有方法的 getHttpClient 方法并返回 CloseableHttpClient 但我无法模拟 httpClient.execute(httpPost) 调用。我得到 null 作为 httpResponse ,因为我期待 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();
    }
}   

【问题讨论】:

    标签: java junit mocking powermock easymock


    【解决方案1】:

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

    【讨论】:

    • 成功了。非常感谢您帮助我解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多