Spring导入测试类内部配置类后Controller未加载报404问题
问题原因
这是Spring Boot切片测试的原生规则导致的:
@WebMvcTest作为Web层切片测试注解,默认会自动注册你指定的HelloController及相关Web组件,同时过滤无关的业务Bean和配置。- 当测试类内部存在标注了
@Configuration的静态内部类时,Spring会将该内部类作为唯一的配置加载来源,直接覆盖切片测试默认的自动注册逻辑,HelloController不会被自动加入容器,因此访问对应接口返回404。
修复方案
推荐用以下方式处理:
将内部配置类的@Configuration注解替换为@TestConfiguration即可。@TestConfiguration是Spring Boot专门为测试场景设计的配置注解,它不会覆盖测试默认的自动配置逻辑,仅会在现有配置基础上补充注册你自定义的HelloService Bean,不会影响HelloController的正常加载。
修改后的核心代码示例:
@ExtendWith(SpringExtension.class) @WebMvcTest(HelloController.class) class HelloControllerIntTest { // 替换为@TestConfiguration @TestConfiguration static class Config { @Bean HelloService getHelloService() { return new HelloService(); } } @Autowired private MockMvc mvc; // 测试方法保持不变 @Test void hello() throws Exception { RequestBuilder request = get("/hello"); MvcResult result = mvc.perform(request).andReturn(); assertEquals("Hello, World", result.getResponse().getContentAsString()); } @Test public void testHelloWithName() throws Exception { mvc.perform(get("/hello?name=Dan")) .andExpect(content().string("Hello, Dan")); } }
测试类内部的@TestConfiguration会被自动扫描到,不需要额外添加@Import注解引入。
内容的提问来源于stack exchange,提问作者szatkus
相关产品推荐
相关产品推荐

