
本文旨在解决在使用中的问题 WebClient 如何在单元测试中使用发送请求? Mockito 模拟以获得预期的响应。本文将分析常见错误,并提供可行的解决方案,包括如何正确 mock WebClient 以及如何处理对象 BodyInserters.fromValue() 方法参数匹配问题。
在使用 Spring WebClient 调用外部服务时,编写单元进行测试和模拟 WebClient 行为至关重要。 然而,不正确的模拟方法会导致测试结果与预期不一致,如返回 HTML 文件而不是期望 JSON 响应。 本文将讨论一个常见的问题 WebClient 模拟问题,并提供清晰的解决方案。
问题分析
问题在于 getResponse 在方法中使用 client 对象很可能不是在测试用例中创建的 mock 对象 (webClientMock)。 如果 client 对象在 getResponse 内部创建方法,即使是方法, mock 了 WebClientBuilder,也不能影响实际使用 WebClient 实例。
解决方案:是的 Mock 的 WebClient 构建方法
为了解决这个问题,建议创建一个可能性 mock 构建的方法 WebClient 实例。 这样,单元测试就可以通过 Mockito 来 stub 这种方法,以确保 getResponse 方法中使用的是 mock 过的 WebClient 对象。
步骤 1:创建 WebClient 构建方法
在你的 service 创建一个专门用于构建类别的类别 WebClient 例如 buildWebClient():
import org.springframework.web.reactive.function.client.WebClient;
import com.google.common.annotations.VisibleForTesting;
public class SomeService {
@VisibleForTesting
WebClient buildWebClient() {
// 使用 WebClientBuilder 构建 WebClient 实例
return WebClient.builder().baseUrl("your_base_url").build(); // 替换你的现实 base URL
}
public String getResponse(String requestBody){
// 使用 buildWebClient() 方法获取 WebClient 实例
WebClient client = buildWebClient();
WebClient.RequestHeadersSpec<?> request =
client.post().body(BodyInserters.fromValue(requestBody));
String resp =
request.retrieve().bodyToMono(String.class)
.doOnError(
WebClientResponseException.class,
err -> {
// do something
})
.block();
return resp;
}
}
- @VisibleForTesting 注释:这是一个来源 Google Guava 图书馆的注释用于表明该方法是为了方便测试而存在的。 这种方法可以避免在生产代码中随意调用。 需要添加Guava依赖,如Maven:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.1-jre</version> </dependency>
步骤 2:在单元测试中 Stub 构建方法
在您的单元测试中使用它 Mockito.doReturn() 方法来 stub buildWebClient() 方法,使其返回 mock 过的 WebClient 对象:
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
public class SomeServiceTest {
@Test
void testGetResponse() {
// 创建 mock 对象
WebClient webClientMock = Mockito.mock(WebClient.class);
WebClient.RequestBodyUriSpec requestBodyUriMock = Mockito.mock(WebClient.RequestBodyUriSpec.class);
WebClient.RequestHeadersSpec requestHeadersMock = Mockito.mock(WebClient.RequestHeadersSpec.class);
WebClient.ResponseSpec responseMock = Mockito.mock(WebClient.ResponseSpec.class);
SomeService someService = new SomeService();
SomeService someServiceSpy = Mockito.spy(someService);
String requestBody = "test_request_body";
// Stub buildWebClient() 方法
Mockito.doReturn(webClientMock).when(someServiceSpy).buildWebClient();
// 设置 mock 对象的行为
when(webClientMock.post()).thenReturn(requestBodyUriMock);
when(requestBodyUriMock.body(eq(BodyInserters.fromValue(requestBody)))).thenReturn(requestHeadersMock);
when(requestHeadersMock.retrieve()).thenReturn(responseMock);
when(responseMock.bodyToMono(String.class)).thenReturn(Mono.just("response"));
// 调用 getResponse 方法
String response = someServiceSpy.getResponse(requestBody);
// 断言结果
assertEquals("response", response);
}
}
步骤 3:处理 BodyInserters.fromValue() 的参数匹配
Mockito 默认使用 equals() 参数匹配的方法。 对于 BodyInserters.fromValue() 方法,直接使用 equals() 可能会因为 BodyInserters.fromValue() 返回的对象可能没有正确实现 equals() 方法。
可以用来解决这个问题。 ArgumentMatchers.eq() 确保参数匹配的准确性:
when(requestBodyUriMock.body(eq(BodyInserters.fromValue(requestBody)))).thenReturn(requestHeadersMock);
总结
通过将 WebClient 提取施工过程到一个可 mock 并在方法中使用 ArgumentMatchers.eq() 该方法可以有效地模拟参数匹配 WebClient 编制可靠的单元测试。 这种方法不仅解决了模拟 WebClient 该问题还提高了代码的可测试性和可维护性。
以上就是使用 Mockito 模拟 WebClient 请注意图灵教育的其他相关文章,以解决单元测试中常见问题的详细内容!