我不确定为什么PowerMockito.when
会返回null
。这是我的课程:
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
}
在第1行中,我将httpResponse
视为空。我想获得一个模拟的HTTPResponse
对象,以便我可以继续前进。
我也试过这个而不是第3行:
CloseableHttpResponse closeableHttpResponse = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(closeableHttpClientMock.execute(httpPost)).thenReturn(closeableHttpResponse);
任何人都可以帮助我吗?
答案 0 :(得分:2)
似乎问题是您在模拟时传递的httpPost
实例与您在执行中传递的实例不同。
解决这个问题的方法是在模拟时使用Matchers.eq(),这样就会在每个对象上执行when
等于你传递的对象:
PowerMockito.when(httpClientMock.execute(Matchers.eq(httpPost)))
.thenReturn(httpResponseMock);