Mockito 是一个 Java 测试框架,用于创建和配置模拟对象(mocks),以便在单元测试中模拟依赖项的行为。Unirest 是一个轻量级的 HTTP 客户端库,用于简化 HTTP 请求和响应的处理。
假设我们有一个使用 Unirest 发送 HTTP 请求的方法:
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
public class HttpClient {
public String fetchData(String url) throws Exception {
HttpResponse<String> response = Unirest.get(url).asString();
return response.getBody();
}
}
我们可以使用 Mockito 来模拟 Unirest 的行为。首先,需要添加 Mockito 和 Unirest 的依赖:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
然后,编写测试用例:
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
public class HttpClientTest {
private HttpClient httpClient;
private Unirest unirest;
@BeforeEach
public void setUp() {
unirest = Mockito.mock(Unirest.class);
httpClient = new HttpClient() {
@Override
protected Unirest getUnirest() {
return unirest;
}
};
}
@Test
public void testFetchData() throws Exception {
String url = "https://example.com/data";
String expectedResponse = "{\"key\":\"value\"}";
HttpResponse<String> mockResponse = Mockito.mock(HttpResponse.class);
when(mockResponse.getBody()).thenReturn(expectedResponse);
when(unirest.get(anyString())).thenReturn(mockResponse);
String actualResponse = httpClient.fetchData(url);
assertEquals(expectedResponse, actualResponse);
}
}
在这个测试用例中,我们通过 Mockito 模拟了 Unirest
和 HttpResponse
的行为。具体步骤如下:
Mockito.mock(Unirest.class)
创建 Unirest
的模拟对象。Mockito.mock(HttpResponse.class)
创建 HttpResponse
的模拟对象,并设置其 getBody
方法的返回值。when(unirest.get(anyString())).thenReturn(mockResponse)
配置 Unirest.get
方法的行为,使其返回模拟的 HttpResponse
对象。httpClient.fetchData(url)
方法,并验证其返回值是否与预期一致。通过这种方式,我们可以在不依赖外部服务的情况下,对 HttpClient
类进行单元测试。
领取专属 10元无门槛券
手把手带您无忧上云