[英]PowerMockito.when returns null
我不確定為什么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
設為 null。 我想獲得一個HTTPResponse
對象,以便我可以進一步進行。
我也試過這個而不是第 3 行:
CloseableHttpResponse closeableHttpResponse = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(closeableHttpClientMock.execute(httpPost)).thenReturn(closeableHttpResponse);
誰能幫我?
似乎問題在於您在httpPost
時傳遞的httpPost
實例與您在執行中傳遞的實例不同。
你能做些什么來解決這個是用Matchers.eq()當你嘲笑,這種方式, when
將每個對象上執行等於你通過一個:
PowerMockito.when(httpClientMock.execute(Matchers.eq(httpPost)))
.thenReturn(httpResponseMock);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.