closeablehttpclient 如何mock
时间: 2023-09-12 20:11:14 浏览: 198
MockObjects
CloseableHttpClient 可以通过 Mockito 进行 mock,具体步骤如下:
1. 首先,导入 Mockito 和 HttpClient 相关的依赖,比如:
```xml
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.26.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
```
2. 创建一个 CloseableHttpClient 实例的工厂类,比如:
```java
public class HttpClientFactory {
public CloseableHttpClient createHttpClient() {
return HttpClients.createDefault();
}
}
```
3. 使用 Mockito 创建 CloseableHttpClient 实例的 mock 对象,并通过 stub 方法返回工厂类的实例,比如:
```java
@Test
public void testCloseableHttpClient() throws IOException {
CloseableHttpClient mockHttpClient = mock(CloseableHttpClient.class);
HttpClientFactory mockHttpClientFactory = mock(HttpClientFactory.class);
when(mockHttpClientFactory.createHttpClient()).thenReturn(mockHttpClient);
// 调用需要使用 CloseableHttpClient 的方法,比如:
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = mockHttpClient.execute(httpGet);
// 断言返回值是否符合预期,比如:
assertEquals(200, response.getStatusLine().getStatusCode());
}
```
通过这种方式,就可以使用 Mockito 创建 CloseableHttpClient 实例,并进行单元测试。需要注意的是,在测试完毕后,需要手动关闭 CloseableHttpResponse 和 CloseableHttpClient,以释放资源。
阅读全文