找不到的方法错误:ExtensionContext$Store.computeIfAbsent,在Spring Boot 4.0.0时发生
在使用Spring Boot和 Testcontainers运行我的集成测试时,我遇到了一个
java.lang.NoSuchMethodError
错误。
错误具体提到:
java.lang.NoSuchMethodError: 'java.lang.Object org.junit.jupiter.api.extension.ExtensionContext$Store.computeIfAbsent(java.lang.Object, java.util.function.Function, java.lang.Class)'
环境:
- Java 21
- Spring Boot(尝试使用最新版本)
- JUnit 5.10.2
- Maven
我的pom.xml片段: 我最近尝试将父版本设为 4.0.0(以为是最新版本),并显式定义了JUnit版本,但错误仍然存在。
XML
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.0</version>
</parent>
<properties>
<junit-jupiter.version>5.10.2</junit-jupiter.version>
</properties>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
最小可重现的测试类:
@SpringBootTest
@ActiveProfiles("test")
public class CarRepositoryAdapterTest {
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@BeforeAll
static void initAll() {
postgres.start();
}
@Test
void shouldSaveAndFindCar() {
// Test logic...
}
}
我已经尝试过的方法:
- 运行
mvn clean install。 - 在依赖中显式添加
junit-jupiter版本5.10.2。 - 错误似乎在测试生命周期的最开始阶段发生(在
SpringExtension.beforeAll期间)。
如何解决这个依赖不匹配?是不是应该使用一个稳定的Spring Boot版本?
解决方案
依赖 spring-boot-starter-test:4.0.5 隐式包含 junit-jupiter:6.0.3。请确保不要在你的 pom.xml 中显式添加这个依赖,因为这会覆盖这个版本。
下面的片段对我有用。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。