1
votes

I'm using EasyMock with PowerMock to mock the external WS call. I could mock the getHttpClient method which is a private method and returns CloseableHttpClient but i'm unable to mock the httpClient.execute(httpPost) call. I'm getting null as httpResponse where as i'm expecting 200 http status code.

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 Case:

@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();
    }
}   
1

1 Answers

2
votes

you need to do Easymock.replay(mockHttpClient,mockResponse) at the end so that mocking activates.