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

如何禁用依赖通过spring.factories注册的Spring工厂且保留该Spring Boot依赖

禁用ResetMocksTestExecutionListener的解决方案

Spring Test默认会合并所有Jar包/META-INF/spring.factories中注册的测试执行监听器,只会累加不会覆盖,所以你之前通过添加自定义spring.factories条目的方式无法排除原有依赖注册的监听器,可通过以下两种方式实现禁用:

  • 局部排除(指定测试类/测试基类生效)

在需要禁用该监听器的测试类,或项目统一的测试父类上添加@TestExecutionListeners注解即可,注意配置合并模式避免丢失其他默认监听器:

import org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;

// 加在测试类或测试基类上
@TestExecutionListeners(
    excludeListeners = ResetMocksTestExecutionListener.class,
    mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
)
public class YourTest {
    // 测试逻辑
}

如果项目多数测试都需要排除,可以把这个注解放到自定义的组合测试注解上,封装后所有测试直接使用自定义注解即可自动应用排除规则。

  • 全局排除(整个项目测试生效)

如果要在全项目范围内禁用该监听器,可在src/test/resources/META-INF/spring.properties中添加以下配置,Spring Test加载监听器时会自动跳过标记为disabled的实现:

spring.test.context.TestExecutionListener.org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener=disabled

内容的提问来源于stack exchange,提问作者Mykola Gurov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:08