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

运行RestController测试类时出现NoClassDefFoundError: WebMvcConfigurer错误

问题解决:RestController测试类抛出NoClassDefFoundError

错误原因分析

java.lang.NoClassDefFoundError: org/springframework/web/servlet/config/annotation/WebMvcConfigurer 通常由以下原因导致:

  • 手动引入的spring-webmvc依赖与Spring Boot版本不兼容,Spring Boot测试组件依赖特定版本的Spring MVC类
  • 测试相关的Spring Boot依赖缺失,导致WebMvcTypeExcludeFilter无法找到所需类
  • 测试类注解冗余,多个注解冲突引发加载异常

解决方案

1. 替换手动依赖为Spring Boot Starter

移除pom.xml中手动添加的spring-webmvc依赖,改用Spring Boot的web starter,它会自动管理所有相关依赖版本,避免冲突:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 确保测试依赖完整

确认pom.xml中包含Spring Boot测试starter,它提供了所有测试所需组件:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

3. 简化测试类注解

@WebMvcTest注解已集成@AutoConfigureWebMvc、@AutoConfigureMockMvc及Mockito自动配置,无需重复添加其他注解,简化后的测试类如下:

@WebMvcTest(Controller.class)
public class ControllerTest {

  @MockBean
  Service service;

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void some_test() throws Exception {
    Mockito.when(service.getSomething())
        .thenReturn(something);
    mockMvc.perform(get("/errors")).andExpect(status().isOk())
        .andExpect(something)
        .andDo(print());
  }
}

4. 刷新依赖并重新构建

执行Maven命令确保依赖正确下载并生效:

mvn clean compile test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:10:30