mockito 创建httpclient
时间: 2023-09-04 21:08:26 浏览: 244
httpclient工具
Mockito 可以用来创建 HttpClient 实例,可以按照以下步骤进行:
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. 创建一个 HttpClient 实例的工厂类,比如:
```java
public class HttpClientFactory {
public HttpClient createHttpClient() {
return HttpClientBuilder.create().build();
}
}
```
3. 使用 Mockito 创建 HttpClient 实例的 mock 对象,并通过 stub 方法返回工厂类的实例,比如:
```java
@Test
public void testHttpClient() {
HttpClient mockHttpClient = mock(HttpClient.class);
HttpClientFactory mockHttpClientFactory = mock(HttpClientFactory.class);
when(mockHttpClientFactory.createHttpClient()).thenReturn(mockHttpClient);
// 调用需要使用 HttpClient 的方法,比如:
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse response = mockHttpClient.execute(httpGet);
// 断言返回值是否符合预期,比如:
assertEquals(200, response.getStatusLine().getStatusCode());
}
```
通过这种方式,就可以使用 Mockito 创建 HttpClient 实例,方便进行单元测试。
阅读全文