You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot WebMvcTest测试Controller返回404问题求助

问题分析与解决方案

你的问题核心在于测试类的上下文配置覆盖了@WebMvcTest的默认行为,导致Spring测试上下文根本没有加载你的RegistroClienteController,所以请求找不到对应的处理器,返回404,断点也不会触发。

具体原因

你在测试类上添加了@ContextConfiguration(classes = { SecurityConfig.class }),这个注解会替换@WebMvcTest默认的组件扫描逻辑——原本@WebMvcTest(RegistroClienteController.class)会自动加载指定的控制器和Spring MVC相关的基础配置,但加上@ContextConfiguration后,Spring只会加载你指定的SecurityConfig.class,完全忽略了控制器类。这就解释了为什么正常启动应用时端点能工作(全量扫描组件),但测试时找不到控制器。

解决方案

有两种可行的修复方式,推荐第一种:

方案1:移除@ContextConfiguration(推荐)

@WebMvcTest已经会自动处理Spring MVC相关的配置,包括安全模块的适配。你已经用@MockBean模拟了UserDetailsService,足够满足安全相关的依赖需求,不需要额外导入SecurityConfig。修改后的测试代码如下:

@RunWith(SpringRunner.class)
@WebMvcTest(RegistroClienteController.class)
public class RegistroClienteControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    UserDetailsService userDetailsService;

    @Test
    public void test() throws Exception {
        //@formatter:off
        mockMvc
                .perform(get("/api/registro-cliente"))
                .andExpect(status().isOk());
        //@formatter:on
    }
}

方案2:如果必须保留SecurityConfig,手动添加控制器到上下文

如果你确实需要在测试中加载完整的SecurityConfig,那么需要把RegistroClienteController也加入@ContextConfiguration的类列表中,确保测试上下文能加载到控制器:

@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration(classes = { SecurityConfig.class, RegistroClienteController.class })
public class RegistroClienteControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    UserDetailsService userDetailsService;

    @Test
    public void test() throws Exception {
        //@formatter:off
        mockMvc
                .perform(get("/api/registro-cliente"))
                .andExpect(status().isOk());
        //@formatter:on
    }
}

验证逻辑

修改后再运行测试,断点应该会正常触发,请求也会返回200。本质上就是确保测试上下文包含了你要测试的控制器类,这样MockMvc才能找到对应的请求处理器。

内容的提问来源于stack exchange,提问作者Fernando Fradegrada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:51:57