I am not sure why PowerMockito.when
returns null
. This is my class under test:
public class A {
public Integer callMethod(){
return someMethod();
}
private Integer someMethod(){
//Some Code
HttpPost httpPost = new HttpPost(oAuthMessage.URL);
//Some Code
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpPost); ------1
Integer code = httpResponse.getStatusLine().getStatusCode(); ---2
return code;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MacmillanServiceImpl.class, PersonService.class, AuthorizeServiceImpl.class, ProvisionHelper.class, ESPHelper.class,
DPFServiceImpl.class, TransactionLogServiceImpl.class, HttpClient.class, HttpEntity.class, InputStream.class, IOUtils.class,
DTOUtils.class, MacmillanESPResponseDTO.class, HttpClientBuilder.class, CloseableHttpClient.class, HttpPost.class, IOUtils.class,
HttpResponse.class, CloseableHttpResponse.class, StatusLine.class })
@PowerMockIgnore({ "javax.crypto.*", "javax.net.ssl.*" })
public class TestA {
//Spying some things here & Injecting them
@Test
public void testA() {
HttpClient httpClientMock = PowerMockito.mock(HttpClient.class);
HttpClientBuilder httpClientBuilderMock = PowerMockito.mock(HttpClientBuilder.class);
CloseableHttpClient closeableHttpClientMock = PowerMockito.mock(CloseableHttpClient.class);
HttpResponse httpResponseMock = PowerMockito.mock(HttpResponse.class);
PowerMockito.mockStatic(HttpClientBuilder.class);
given(HttpClientBuilder.create()).willReturn(httpClientBuilderMock);
when(httpClientBuilderMock.build()).thenReturn(closeableHttpClientMock);
PowerMockito.when(httpClientMock.execute(httpPost)).thenReturn(httpResponseMock); --This does not work----Line 3
//Other codes
//call the method
}
In line-1 I get httpResponse
as null. I want to get a mocked HTTPResponse
object so that I can proceed further.
I have also tried this instead of Line 3:
CloseableHttpResponse closeableHttpResponse = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(closeableHttpClientMock.execute(httpPost)).thenReturn(closeableHttpResponse);
Can anyone help me?
Seems that the issue is that the httpPost
instance that you pass when mocking is not the same as the one you pass in the execution.
What you can do to resolve this is use Matchers.eq() when you mock, that way the when
will be executed on every object equals to the one you pass:
PowerMockito.when(httpClientMock.execute(Matchers.eq(httpPost)))
.thenReturn(httpResponseMock);