Spring Cloud Contract测试出现NoClassDefFoundError问题求助
问题原因分析
- Jakarta EE 包路径变更:Spring Boot 3.x 基于 Jakarta EE 9+,所有原
javax.*包已替换为jakarta.*,报错中的javax/servlet/Filter属于旧 Java EE 包,说明测试运行时缺少对应 Jakarta Servlet API 的测试依赖。 - 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
相关产品推荐
相关产品推荐

