Spring Boot 3中MockWebServer与WebTestClient测试遇404 NOT_FOUND错误
Spring Boot 3升级中MockWebServer + WebTestClient测试404问题排查
问题背景
升级Spring Boot 3后,使用MockWebServer和WebTestClient编写JUnit测试模拟API时,遇到404 NOT_FOUND错误。使用的okhttp版本为4.10.0,依赖配置如下:
testImplementation("com.squareup.okhttp3:mockwebserver:4.10.0") testImplementation("com.squareup.okhttp3:okhttp:4.10.0")
测试代码片段:
@LocalServerPort private int port = 0; @BeforeEach public void setup() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(8034); baseUri = "http://localhost:" + port; this.webClient = WebTestClient.bindToServer().responseTimeout(Duration.ofSeconds(10)).baseUrl(baseUri).build(); } @WithMockUser(authorities = "csn") @Test public void contextLoadsWithRoutedRequestOk() { mockWebServer.enqueue(new MockResponse().setResponseCode(200)); webClient.get().uri("/test").exchange().expectStatus().isOk(); }
问题根源
代码里存在两个核心错误导致404:
- WebTestClient的
baseUrl指向了@LocalServerPort对应的真实应用端口,而非MockWebServer启动的8034端口,请求实际发向了真实服务,但真实服务中没有/test接口,因此返回404。 - MockWebServer虽启动了8034端口,但WebTestClient并未向该端口发起请求,导致你配置的MockResponse完全没被用到。
修复方案
修改setup方法,将WebTestClient的baseUrl指向MockWebServer的地址即可:
@BeforeEach public void setup() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(8034); // 改用MockWebServer的地址作为baseUrl baseUri = mockWebServer.url("/").toString(); this.webClient = WebTestClient.bindToServer().responseTimeout(Duration.ofSeconds(10)).baseUrl(baseUri).build(); }
如果想避免端口冲突,也可以让MockWebServer使用随机端口:
@BeforeEach public void setup() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(); // 不指定端口,随机分配 baseUri = mockWebServer.url("/").toString(); this.webClient = WebTestClient.bindToServer().responseTimeout(Duration.ofSeconds(10)).baseUrl(baseUri).build(); }
内容的提问来源于stack exchange,提问作者sekhar
相关产品推荐
相关产品推荐

