Spring Boot 4.x与3.x中@WebMvcTest的安全行为差异及原因咨询
Spring Boot 4.x与3.x中@WebMvcTest的安全行为差异及原因咨询
更新说明:补充了我的测试观察结果
我最近在学习Spring Security,使用@WebMvcTest编写测试时遇到了一个困惑,想请教大家:
情况一:Spring Boot 4.0.3项目
- 依赖配置:包含
spring-boot-starter-webmvc、spring-boot-starter-webmvc-test、spring-boot-starter-security - 未引入
spring-boot-starter-security-test依赖 - 项目中没有任何自定义的安全配置类
控制器代码
@RestController public class DemoController { @GetMapping("/hello") public String hello() { return "Hello"; } }
测试类代码
@WebMvcTest(DemoController.class) @AutoConfigureRestTestClient class DemoControllerTest { @Autowired private RestTestClient restClient; @Autowired private MockMvc mockMvc; @Autowired private MockMvcTester mockMvcTester; @Test void test_hello_001() { restClient.get() .uri("/hello") .exchange() .expectStatus() .isOk() .expectBody(String.class) .isEqualTo("Hello"); } @Test void test_hello_002() { Assertions.assertThat(mockMvcTester.get() .uri("/hello")) .hasStatusOk() .hasBodyTextEqualTo("Hello"); } @Test void test_hello_003() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(MockMvcResultMatchers.status() .isOk()) .andExpect(MockMvcResultMatchers.content() .string("Hello")); } }
测试结果
- 三个测试方法都能正常通过,不需要添加
@WithMockUser或者自定义安全配置 - 但是一旦我在pom.xml中加入
spring-boot-starter-security-test依赖,所有测试都会失败,报错信息如下:java.lang.AssertionError: Status expected:<200 OK> but was:<401 UNAUTHORIZED> Expected :200 OK Actual :401 UNAUTHORIZED
情况二:Spring Boot 3.5.11项目
- 依赖配置:包含
spring-boot-starter-web、spring-boot-starter-test、spring-boot-starter-security - 未引入
spring-security-test依赖 - 项目中同样没有任何自定义的安全配置类
控制器代码
@RestController public class DemoController { @GetMapping("/hello") public String hello() { return "Hello"; } }
测试类代码
@WebMvcTest(DemoController.class) // @AutoConfigureRestTestClient class DemoControllerTest { // @Autowired // private RestTestClient restClient; @Autowired private MockMvc mockMvc; @Autowired private MockMvcTester mockMvcTester; // @Test // void test_hello_001() { // restClient.get() // .uri("/hello") // .exchange() // .expectStatus() // .isOk() // .expectBody(String.class) // .isEqualTo("Hello"); // } @Test void test_hello_002() { Assertions.assertThat(mockMvcTester.get() .uri("/hello")) .hasStatusOk() .hasBodyTextEqualTo("Hello"); } @Test void test_hello_003() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(MockMvcResultMatchers.status() .isOk()) .andExpect(MockMvcResultMatchers.content() .string("Hello")); } }
注:
test_hello_001方法被注释是因为RestTestClient在Spring Boot 3.5.11版本中还不可用
测试结果
- 不管有没有引入
spring-security-test依赖,这两个测试方法都会失败 - 只要给测试方法加上
@WithMockUser注解,测试就能正常通过,这和我预期的行为一致
我的疑问
Spring Boot 3.5.11的测试行为我能理解,但为什么Spring Boot 4.0.3的测试在没有@WithMockUser和自定义安全配置的情况下就能正常通过?而且引入spring-boot-starter-security-test依赖后反而会失败呢?
备注:内容来源于stack exchange,提问作者Saravana Kumar M
相关产品推荐
相关产品推荐

