升到 Boot 4 后测试里的 TestRestTemplate 和 @AutoConfigureRestTestClient 为什么找不到?要换哪个包、加哪个依赖?RestTestClient 在 MOCK 和 RANDOM_PORT 下有什么不同?这篇在 Spring Boot 4.0.8 上逐个编译、运行。
-- bindToController:不要 Spring 容器
[旧依赖] bindToController:不启动 Spring 容器,GET /users/1 断言 $.name = user-1 通过 通过
-- bindToApplicationContext:@SpringBootTest 的容器
[旧依赖] bindToApplicationContext:响应体 {"id":2,"name":"user-2","port":80} 通过bindToController 与 bindToApplicationContext 只需要 starter-test。
-- 旧依赖下
[旧依赖] 编译失败:package org.springframework.boot.resttestclient.autoconfigure does not exist
-- 新依赖下
[新依赖] 随机端口 + @AutoConfigureRestTestClient:服务器端口 已分配,响应体 {"id":3,"name":"user-3","port":<端口>},响应里的 port 就是服务器端口 通过@AutoConfigureRestTestClient 在新模块里,旧依赖编译失败。
-- 新依赖下
[新依赖] MOCK 环境 + @AutoConfigureRestTestClient:响应体 {"id":4,"name":"user-4","port":80} 通过同一个注解,MOCK 环境下 port 是 80,没有启动服务器。
-- jsonPath 值不对 [旧依赖] (没有输出) [失败,退出码 1:java.lang.AssertionError: JSON path "$.name" expected:<wrong> but was:<user-1>] -- 状态码不对(访问不存在的路径) [旧依赖] (没有输出) [失败,退出码 1:java.lang.AssertionError: Status expected:<200 OK> but was:<404 NOT_FOUND>]
报错信息带着期望值和实际值。
-- Boot 3 的写法(org.springframework.boot.test.web.client.TestRestTemplate)
[旧依赖] 编译失败:package org.springframework.boot.test.web.client does not exist | cannot find symbol
[新依赖] 编译失败:package org.springframework.boot.test.web.client does not exist | cannot find symbol
-- 新位置的 TestRestTemplate,没有加 @AutoConfigureTestRestTemplate
[新依赖] (没有输出) [失败,退出码 1: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.resttestclient.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Au]
-- 新位置的 TestRestTemplate,加了 @AutoConfigureTestRestTemplate
[新依赖] (没有输出) [失败,退出码 1: java.lang.ClassNotFoundException: org.springframework.boot.restclient.RestTemplateBuilder]
[新依赖+restclient] {"id":1,"name":"user-1","port":<端口>} 通过换包名、加注解、加 starter-restclient,三个条件缺一个都不行。