HttpClient Выполнить, возвращая нулевой HttpResponse в TestCases - PullRequest
0 голосов
/ 07 октября 2019

Я писал тестовые случаи для метода, который использует HttpClient как:

public String someMethod(para1, para2){
HttpResponse response = getHttpPostResponse(url,requestBody);
int statusCode = response.getStatusLine().getStatusCode();
}

А метод HttpPost Response имеет вид:

private HttpResponse getHttpPostResponse(String url, String requestBody) throws IOException{

HttpHost proxy = new HttpHost(“someProxy”, 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).build();

HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", System.getenv(“token”));
httpPost.addHeader("Content-Type", "application/json");

StringEntity body = new StringEntity(requestBody);
body.setContentType("application/json");
httpPost.setEntity(body);

return httpClient.execute(httpPost);

}

Я пишу тестовые примеры как:

@Test
public void testExecutiveBriefingWithoutCache() throws Exception {

ClassName spy = PowerMockito.spy(new Class);
CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
HttpClientBuilder httpClientBuilder = mock(HttpClientBuilder.class);
PowerMockito.mockStatic(HttpClientBuilder.class);
HttpPost httpPost = mock(HttpPost.class);

when(statusLine.getStatusCode()).thenReturn(200);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
when(httpClientBuilder.build()).thenReturn(httpClient);
when(httpClient.execute(httpPost)).thenReturn(httpResponse);

PowerMockito.doReturn(httpResponse).when(spy,"getHttpPostResponse”,url,requestBody);
String result = spy.someMethod(para1, para2);

}

Но я получаю httpResponse как ноль и получаю исключение нулевого указателя, когда я

    int statusCode = response.getStatusLine().getStatusCode();
...