使用try-with-resources仍遇Mockito静态模拟已注册错误求助
问题:Mockito静态Mock多测试类执行时冲突,try-with-resources未正常清理
我有一个工具类ConverterUtil,包含方法convertJsonToFileBytes,还有两个测试类WorkflowExportServiceTest和WorkflowExportControllerTest。单独运行每个测试类一切正常,但批量执行所有测试时出现报错:
[ERROR] Errors: [ERROR] WorkflowExportServiceTest.given_workflowId_shouldConvertToJSONFile:60 Mockito For com.closeupinternational.baseproject.util.ConverterUtil, static mocking is already registered in the current thread To create a new mock, the existing static mock registration must be deregistered
测试类代码
WorkflowExportServiceTest
@SpringBootTest(properties = "spring.cloud.config.enabled=false") @Slf4j class WorkflowExportServiceTest { ... @Test void given_workflowId_shouldConvertToJSONFile() throws IOException { try (MockedStatic<ConverterUtil> utilities = Mockito.mockStatic(ConverterUtil.class)) { utilities.when(() -> ConverterUtil.convertJsonToFileBytes(any(), any(), any())).thenReturn(new byte[0]); ... } }
WorkflowExportControllerTest
@ExtendWith(SpringExtension.class) @WebMvcTest(WorflowExportController.class) class WorkflowExportControllerTest { ... @Test void given_workflowId_shouldReturnJsonExportedFromWorkflow() throws Exception { try(MockedStatic<ConverterUtil> utilities = Mockito.mockStatic(ConverterUtil.class)){ utilities.when(() -> ConverterUtil.convertJsonToFileBytes(any(),any(),any())).thenReturn(new byte[0]); ... } }
pom.xml相关配置
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> ... <properties> <spring-cloud.version>2023.0.3</spring-cloud.version> <maven.compiler.source>21</maven.compiler.source> <maven.compiler.target>21</maven.compiler.target> <java.version>21</java.version> ... </properties> ... <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-inline</artifactId> <version>5.2.0</version> <scope>test</scope> </dependency>
补充说明:一个是控制器测试,另一个是服务测试。MockedStatic来自mockito-core:5.11.0
问题原因
- 线程绑定与复用:Mockito的
MockedStatic是绑定到当前线程的,Spring测试框架批量执行测试时可能复用线程。即使try-with-resources会调用close(),如果线程被复用,前一个测试的静态Mock注册信息可能未完全清理,导致后续测试创建新Mock时冲突。 - 依赖版本不一致:mockito-inline版本为5.2.0,但mockito-core是5.11.0,版本不匹配可能导致资源清理逻辑异常。
解决方案
1. 统一Mockito依赖版本
确保mockito-inline和mockito-core版本一致,避免版本冲突:
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-inline</artifactId> <version>5.11.0</version> <scope>test</scope> </dependency>
2. 显式清理静态Mock
在每个测试类中添加@AfterEach方法,强制清理线程中的静态Mock注册:
@AfterEach void tearDown() { Mockito.framework().clearInlineMocks(); }
3. 禁用测试上下文缓存
给测试类添加@DirtiesContext注解,强制每个测试类结束后销毁上下文,避免线程复用:
@SpringBootTest(properties = "spring.cloud.config.enabled=false") @Slf4j @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) class WorkflowExportServiceTest { // ... 测试代码 } @ExtendWith(SpringExtension.class) @WebMvcTest(WorflowExportController.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) class WorkflowExportControllerTest { // ... 测试代码 }
4. 重构工具类为非静态(推荐)
将ConverterUtil改为Spring组件,通过依赖注入使用,用普通Mock代替静态Mock,从根源解决问题:
@Component public class ConverterUtil { public byte[] convertJsonToFileBytes(...) { // ... 原逻辑 } } // 服务类中注入 @Service public class WorkflowExportService { private final ConverterUtil converterUtil; public WorkflowExportService(ConverterUtil converterUtil) { this.converterUtil = converterUtil; } } // 测试用@MockBean替代静态Mock @SpringBootTest(properties = "spring.cloud.config.enabled=false") @Slf4j class WorkflowExportServiceTest { @MockBean private ConverterUtil converterUtil; @Test void given_workflowId_shouldConvertToJSONFile() throws IOException { when(converterUtil.convertJsonToFileBytes(any(), any(), any())).thenReturn(new byte[0]); // ... 测试逻辑 } }
内容的提问来源于stack exchange,提问作者Aldo Inácio da Silva
相关产品推荐
相关产品推荐

