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

Spring Boot Controller测试:断言静态HTML响应无内容问题排查

问题分析与解决方案

你遇到的核心问题是:@WebMvcTest 注解默认只会加载Spring MVC的核心组件(控制器、请求转换器、拦截器等),不会自动配置静态资源的处理逻辑。当你的控制器返回 "index.html" 时,MockMvc找不到对应的资源处理器来读取静态目录下的文件,所以响应内容为空。

下面提供两种无需启动完整服务器的解决方案:

方案1:导入完整WebMvc自动配置类

直接在测试类上导入WebMvcAutoConfiguration,这个配置类包含了静态资源映射、视图解析等完整的WebMvc配置:

@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
@Import(WebMvcAutoConfiguration.class) // 引入静态资源处理的配置
@AutoConfigureMockMvc
public class IndexControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnIndexPage() throws Exception {
        File index = new ClassPathResource("static/index.html").getFile();
        String html = new Scanner(index).useDelimiter("\\z").next();
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string(html));
    }
}

方案2:手动配置静态资源映射

如果不想导入完整的WebMvc配置,也可以在测试类内部自定义静态资源的映射规则:

@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
@AutoConfigureMockMvc
public class IndexControllerTest {
    @Autowired
    private MockMvc mockMvc;

    // 自定义静态资源映射配置
    @Configuration
    static class TestStaticResourceConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // 映射所有请求到static目录下查找资源
            registry.addResourceHandler("/**")
                    .addResourceLocations("classpath:/static/");
        }
    }

    @Test
    public void shouldReturnIndexPage() throws Exception {
        File index = new ClassPathResource("static/index.html").getFile();
        String html = new Scanner(index).useDelimiter("\\z").next();
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string(html));
    }
}

额外小贴士

如果你的测试不需要严格验证HTML内容,只需要确认请求能正常返回正确的视图,其实可以简化测试逻辑,这样更轻量:

@Test
public void shouldReturnIndexPage() throws Exception {
    mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index.html"));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:28:05