Spring-Data-Mongo-Reactive嵌套测试Mongo连接关闭问题咨询
解决方案
问题根因
该报错是嵌套测试执行时Spring上下文提前销毁,导致Reactive MongoDB的服务端会话池、连接池被提前关闭所致,本质原因是JUnit 5的@Nested嵌套测试类默认未继承外层测试的上下文配置,或是测试资源生命周期绑定错误。
修复步骤
- 给嵌套测试类添加
@NestedTestConfiguration注解,指定继承外层测试配置,复用同一个Spring上下文,避免上下文重复创建销毁 - 将测试类中的配置常量改为
static修饰,避免@EnabledIf注解解析时触发上下文重复加载 - 确保Testcontainers的MongoDB容器为静态类资源,生命周期绑定到整个测试类而非单测试方法,避免测试方法执行完成后容器被提前停止
- 移除测试配置中方法级别的
@DirtiesContext注解,避免每个测试方法执行完就销毁上下文,如有清理需要可改为类级别的@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
修复后代码示例
import org.springframework.test.context.NestedTestConfiguration; import static org.springframework.test.context.NestedTestConfiguration.EnclosingConfiguration.INHERIT_OVERRIDES; @Import(ServiceCrudRepoCfg.class) @TestcontainerAnn @TestsMongoConfigAnn @TestsGlobalAnn public class Lab { // 改为static常量 final static private String enabledTest = "true"; @Autowired IService serviceCrudRepo; @Test @DisplayName("Save") @EnabledIf(expression = enabledTest, loadContext = true) public void save() { Person localPerson = personWithIdAndName().create(); StepVerifier .create(serviceCrudRepo.save(localPerson)) .expectSubscription() .expectNext(localPerson) .verifyComplete(); } @Nested @DisplayName("Nested Class") @Execution(SAME_THREAD) // 添加嵌套测试配置继承注解 @NestedTestConfiguration(INHERIT_OVERRIDES) class NestedClass { @Test @DisplayName("findAll") @EnabledIf(expression = enabledTest, loadContext = true) public void findAll() { StepVerifier .create(serviceCrudRepo.findAll() .log()) .expectSubscription() .expectNextCount(1L) .verifyComplete(); } } }
额外排查点
如果修改后仍然报错,可检查你的@TestsMongoConfigAnn自定义配置中,MongoClient的作用域是否为单例,是否存在测试方法执行完主动关闭MongoClient的逻辑。
内容的提问来源于stack exchange,提问作者GtdDev
相关产品推荐
相关产品推荐

