SpringBoot测试用例抛出IllegalStateException问题求助
问题排查与解决方案
核心原因
@WebMvcTest 是Spring Boot的切片测试注解,仅会加载Web层相关组件(控制器、请求处理器、过滤器等),不会自动初始化数据访问层(如Repository)、业务层的Bean。如果你的ErrorController(或其依赖的组件)中注入了SpringSessionRepository,测试上下文启动时就会因找不到该Bean而抛出依赖注入失败的异常。
解决方法
1. 模拟缺失的Repository Bean
如果测试逻辑不依赖SpringSessionRepository的真实实现,直接用@MockBean在测试类中创建一个模拟Bean即可:
@WebMvcTest(ErrorController.class) class ErrorControllerTest { // 模拟SpringSessionRepository,解决依赖缺失问题 @MockBean private SpringSessionRepository springSessionRepository; @Autowired private MockMvc mockMvc; // 你的测试方法 @Test void testErrorPage() throws Exception { mockMvc.perform(get("/error")) .andExpect(status().isOk()); } }
2. 切换到完整上下文测试
如果测试需要依赖SpringSessionRepository的真实行为(比如验证会话相关逻辑),放弃切片测试,改用@SpringBootTest配合@AutoConfigureMockMvc加载完整ApplicationContext:
@SpringBootTest @AutoConfigureMockMvc class ErrorControllerTest { @Autowired private MockMvc mockMvc; // 测试方法... }
注意:这种方式启动速度会比切片测试慢,适合需要完整上下文的集成测试场景。
3. 手动注册测试用Bean
如果需要自定义SpringSessionRepository的测试实现,可以通过@TestConfiguration在测试类中手动注册Bean:
@WebMvcTest(ErrorController.class) class ErrorControllerTest { // 测试专用配置类,注册自定义的SpringSessionRepository实现 @TestConfiguration static class TestConfig { @Bean public SpringSessionRepository springSessionRepository() { return new TestSpringSessionRepository(); // 自定义测试实现 } } @Autowired private MockMvc mockMvc; // 测试方法... }
额外检查点
- 确认
ErrorController是否直接注入了SpringSessionRepository,或者是否通过其他组件(比如会话管理服务)间接依赖了它。 - 检查项目中是否存在自定义的Session配置类,确保测试环境下该配置类能被正确扫描到(如果需要真实Bean的话)。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

