我正在尝试为 http post 实现编写一个单元测试。但是,我无法正确模拟 httpclient,并且我的 when 语句永远不会被触发。我编写的单元测试是进行实际的 http 调用,而不是使用模拟响应进行响应。我们如何继续模拟 HttpClientBuilder 创建的客户端?
Http方法实现:
HttpResponse postRequest(String url, String request) {
HttpResponse resp = null;
try {
HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity(request));
resp = client.execute(post);
} catch (Exception e) {
return null;
}
}
测试方法:
@Mock
private HttpClient httpClient;
when(httpClient.execute(any())).thenReturn(httpResponse);
饮歌长啸
相关分类