SpringBoot3&SpringSecurity6下MockMvc测试404及上下文加载失败求助
问题解决方案
一、解决MockMvc测试404错误
初始测试出现404的核心原因是测试类注解冲突:
@WebMvcTest(UserController.class)已包含@ExtendWith(SpringExtension.class)、@WebAppConfiguration的功能,且会自动加载目标Controller和Spring MVC相关配置。- 手动添加
@ContextConfiguration(classes = SecurityConfig.class)会覆盖默认上下文,导致Spring仅加载SecurityConfig,未加载UserController,请求路径无对应处理器,返回404。
修正后的测试类
@WebMvcTest(UserController.class) class UserControllerTest { @Autowired private MockMvc mockMvc; @Test @DisplayName("Get check") void getCheck() throws Exception { mockMvc.perform(get("/login/hi")) .andDo(print()) .andExpect(status().isOk()); } }
二、解决ApplicationContext加载失败(找不到UserService Bean)
补充代码后,更新的SecurityConfig依赖了UserService,但@WebMvcTest是Web层切片测试,仅加载Controller、Spring MVC配置等Web相关组件,不会自动扫描初始化Service、Repository等业务层Bean,因此出现Bean找不到的错误。
方案1:用@MockBean模拟UserService
通过@MockBean创建一个模拟的UserService Bean,满足SecurityConfig的依赖需求,适合仅测试Web层逻辑的场景:
@WebMvcTest(UserController.class) @Import(SecurityConfig.class) // 若SecurityConfig不在默认扫描路径,手动导入 class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; // 模拟业务层Bean,解决依赖缺失问题 @Test @DisplayName("Get check") void getCheck() throws Exception { mockMvc.perform(get("/login/hi")) .andDo(print()) .andExpect(status().isOk()); } }
方案2:改用@SpringBootTest加载完整上下文
如果需要测试完整的业务流程(包括Service、Repository的真实逻辑),改用@SpringBootTest配合@AutoConfigureMockMvc,会加载整个应用的ApplicationContext:
@SpringBootTest @AutoConfigureMockMvc class UserControllerTest { @Autowired private MockMvc mockMvc; @Test @DisplayName("Get check") void getCheck() throws Exception { mockMvc.perform(get("/login/hi")) .andDo(print()) .andExpect(status().isOk()); } }
额外优化建议
移除UserController上的@EnableWebMvc注解:该注解会关闭Spring Boot自动配置的Spring MVC特性,若没有自定义全部MVC配置的需求,保留自动配置更省心。
内容的提问来源于stack exchange,提问作者bc a
相关产品推荐
相关产品推荐

