Spring响应式框架WebClient Builder的JUnit测试用例编写问询
为Spring WebClient GET请求编写JUnit测试用例
要测试你这段WebClient的GET请求,我们可以用MockWebServer模拟后端服务,结合WebClient.Builder来验证请求的正确性并预设响应,完全不需要依赖真实的8080服务。
依赖准备
确保你的测试依赖包含这些核心库:
spring-boot-starter-webflux:提供WebClient支持spring-boot-starter-test:包含JUnit 5、MockWebServer等测试工具okhttp3:MockWebServer的底层依赖
测试代码示例
先假设你的WebClient请求封装在一个业务类里(比如EmployeeService):
@Service public class EmployeeService { private final WebClient webClient; public EmployeeService(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl("http://localhost:8080").build(); } public Mono<String> getEmployeeById(String id) { return webClient.get() .uri("/employee/{id}", id) .retrieve() .bodyToMono(String.class); } }
对应的JUnit 5测试用例:
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.web.reactive.function.client.WebClient; import reactor.test.StepVerifier; import java.io.IOException; class EmployeeServiceTest { private static MockWebServer mockWebServer; private EmployeeService employeeService; @BeforeAll static void startMockServer() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(); } @BeforeEach void initService() { String mockBaseUrl = String.format("http://localhost:%d", mockWebServer.getPort()); WebClient.Builder webClientBuilder = WebClient.builder().baseUrl(mockBaseUrl); employeeService = new EmployeeService(webClientBuilder); } @Test void getEmployeeById_ShouldReturnExpectedData() { // 预设模拟响应 String mockEmployeeJson = "{\"id\":\"xyz\",\"name\":\"Test Employee\"}"; mockWebServer.enqueue(new MockResponse() .setBody(mockEmployeeJson) .addHeader("Content-Type", "application/json")); // 调用待测试方法 Mono<String> result = employeeService.getEmployeeById("xyz"); // 验证响应式流的结果 StepVerifier.create(result) .expectNext(mockEmployeeJson) .verifyComplete(); // 验证实际发送的请求是否符合预期 var recordedRequest = mockWebServer.takeRequest(); assert recordedRequest.getMethod().equals("GET"); assert recordedRequest.getPath().equals("/employee/xyz"); } @AfterAll static void stopMockServer() throws IOException { mockWebServer.shutdown(); } }
核心要点
- MockWebServer:模拟后端服务,捕获发送的请求并返回预设响应,彻底隔离外部依赖
- StepVerifier:Reactor提供的工具,专门用于验证响应式流的输出是否符合预期
- 请求校验:通过
takeRequest()拿到实际发送的请求,验证请求方法、路径等参数是否正确
内容的提问来源于stack exchange,提问作者Gaurav Khandelwal
相关产品推荐
相关产品推荐

