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

Spring Cloud Contract测试出现NoClassDefFoundError问题求助

问题原因分析
  1. Jakarta EE 包路径变更:Spring Boot 3.x 基于 Jakarta EE 9+,所有原 javax.* 包已替换为 jakarta.*,报错中的 javax/servlet/Filter 属于旧 Java EE 包,说明测试运行时缺少对应 Jakarta Servlet API 的测试依赖。
  2. Spring Security 集成缺失:原 BaseTestClass 使用 RestAssuredMockMvc.standaloneSetup 直接注册控制器,未加载完整 Spring 上下文(包括 Spring Security 的过滤器链),导致测试无法处理 Servlet 相关逻辑及 Security 配置。
解决方案

1. 添加 Jakarta Servlet API 测试依赖

在 Maven pom.xml 中加入测试范围的 Jakarta Servlet API 依赖:

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>test</scope>
</dependency>

2. 重构 BaseTestClass 以集成 Spring Security

改用 @WebMvcTest 加载 MVC 相关上下文(包括 Spring Security 配置),并让 RestAssuredMockMvc 使用 Spring 注入的 MockMvc:

import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.mockMvc;

@ActiveProfiles("test")
@WebMvcTest({AuthorizationController.class, IdentityController.class})
public abstract class BaseTestClass {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AuthorizationService authorizationService;

    @MockBean
    private IdentityService identityService;

    @BeforeEach
    public void setup() {
        // 绑定Spring的MockMvc到RestAssuredMockMvc,自动包含Security过滤器链
        mockMvc(this.mockMvc);
    }
}
  • @WebMvcTest 会自动配置 Spring MVC 核心组件及 Spring Security 过滤器,解决手动 standaloneSetup 无法加载 Security 配置的问题。
  • 通过 mockMvc(this.mockMvc) 让 RestAssured 复用 Spring 管理的 MockMvc,避免出现 spring test delegate cannot be null 错误。

3. 确认 Spring Cloud Contract 插件配置正确性

确保插件指定了正确的测试基类,且版本与 Spring Boot 3.x 兼容:

<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>4.0.1</version>
    <extensions>true</extensions>
    <configuration>
        <baseClassForTests>com.projectId.artifactId.contracts.BaseTestClass</baseClassForTests>
        <!-- 其他契约仓库、生成规则等配置 -->
    </configuration>
</plugin>

4. 空项目添加 Spring Security 后的适配

对于空项目中出现的 IllegalState 或 delegate null 错误,同样采用上述 @WebMvcTest 配置替代手动 standaloneSetup,让 Spring 完整加载 MVC 和 Security 上下文,即可解决启动问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:10:05