Pop*_*orn 17 java mocking mockito apache-commons-httpclient
我正在尝试构建一个CloseableHttpResponse模拟对象,以便在我的一个单元测试中返回,但是它没有构造函数.我找到了这个DefaultHttpResponseFactory,但它只生成一个HttpResponse.构建CloseableHttpResponse的简单方法是什么?我是否需要调用execute()我的测试然后设置statusLine和entity?这似乎是一种奇怪的方法.
这是我试图模拟的方法:
public static CloseableHttpResponse getViaProxy(String url, String ip, int port, String username,
String password) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(ip, port),
new UsernamePasswordCredentials(username, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
RequestConfig config = RequestConfig.custom()
.setProxy(new HttpHost(ip, port))
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
LOGGER.info("executing request: " + httpGet.getRequestLine() + " via proxy ip: " + ip + " port: " + port +
" username: " + username + " password: " + password);
CloseableHttpResponse response = null;
try {
return httpclient.execute(httpGet);
} catch (Exception e) {
throw new RuntimeException("Could not GET with " + url + " via proxy ip: " + ip + " port: " + port +
" username: " + username + " password: " + password, e);
} finally {
try {
response.close();
} catch (Exception e) {
throw new RuntimeException("Could not close response", e);
}
}
} finally {
try {
httpclient.close();
} catch (Exception e) {
throw new RuntimeException("Could not close httpclient", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用PowerMockito的模拟代码:
mockStatic(HttpUtils.class);
when(HttpUtils.getViaProxy("http://www.google.com", anyString(), anyInt(), anyString(), anyString()).thenReturn(/*mockedCloseableHttpResponseObject goes here*/)
Run Code Online (Sandbox Code Playgroud)
小智 26
请按照以下步骤操作:
1.模拟它(例如mockito)
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
HttpEntity entity = mock(HttpEntity.class);
Run Code Online (Sandbox Code Playgroud)
2.适用一些规则
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
when(entity.getContent()).thenReturn(getClass().getClassLoader().getResourceAsStream("result.txt"));
when(response.getEntity()).thenReturn(entity);
Run Code Online (Sandbox Code Playgroud)
3.使用它
when(httpClient.execute((HttpGet) any())).thenReturn(response);
Run Code Online (Sandbox Code Playgroud)
nvm,我最终只是使用以下方法破解了它execute():
private CloseableHttpResponse getMockClosesableHttpResponse(HttpResponse response) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse closeableHttpResponse = httpClient.execute(new HttpGet("http://www.test.com"));
closeableHttpResponse.setEntity(response.getEntity());
closeableHttpResponse.setStatusLine(response.getStatusLine());
return closeableHttpResponse;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18497 次 |
| 最近记录: |