Search code examples
javaunit-testingmockitopowermockpowermockito

How to mock an object's method using PowerMockito?


I have a class which contains a method which I want to test. Here's the class.

class classOne {
private static boolean doneThis = false;
methodOne() {
 CloseableHttpResponse response = SomeClass.postData(paramOne, paramTwo);
                log.info("res - {}", response.getStatusLine().getStatusCode());
                doneThis = true;
}
}

Now, I want to mock the response.getStatusLine().getStatusCode() part using PowerMockito.

How can I acheive this? This is what I have done, but it is (the 2nd line below) getting NullPointerException.

CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(response.getStatusLine().getStatusCode()).thenReturn(200);

This is how I am mocking the Someclass.postData ->

PowerMockito.mockStatic(SomeClass.class);
ParamOne paramOne = new ParamOne(..);
// same for paramTwo    
   PowerMockito.when(SomeClass.postData(paramOne,paramTwo)).thenReturn(response);

Updated code:

CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class);
StatusLine statusLine = PowerMockito.mock(StatusLine.class);
PowerMockito.when(response.getStatusLine()).thenReturn(statusLine);
PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);

Problem is, the mocked getStatusCode() is returning the expected value in the Test method - but in case of the actual class, the lines next to it are not being covered, i.e, the test is failing at that point. Workaround?


Solution

  • Of course you first have to mock

    response.getStatusLine()
    

    otherwise the default return value is null and calling .getStatusCode() on null leads to a NullPointerException.

    CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class);
    ? statusLine = PowerMockito.mock(?.class);
    PowerMockito.when(response.getStatusLine()).thenReturn(statusLine);
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
    

    Replace ? with the actual class of statusLine.