You need to enable JavaScript to run this app. JUnit测试随机顺序运行时出现UnfinishedStubbingException问题求助
优惠活动
大模型
产品
解决方案
定价
更多

JUnit测试随机顺序运行时出现UnfinishedStubbingException问题求助

问题描述

执行Maven命令 mvn -Dsurefire.runOrder=random clean test 以随机顺序运行测试时,以下测试用例出现失败,但使用 mvn clean install 按正常顺序运行或本地单独运行时无异常:

@Test
public void ShouldReturnCorrectAccountLoanSumForDebtRatioWhenRedemptionAmountIsNull(){
    AccountVO account = mock(AccountVO.class);
    CustomerGroupInformationVO group = mock(CustomerGroupInformationVO.class);
    when(group.getCustomerIds()).thenReturn(Set.of("199406208123"));
    when(account.getAccountOwners()).thenReturn(List.of((new AccountOwnerVO(null, "199406208123", null))));
    when(account.getAmount()).thenReturn(BigDecimal.valueOf(500000));
    when(account.getRedemptionAmount()).thenReturn(null);

    assertEquals(BigDecimal.valueOf(500000), getAdjustedAccountLoanSumForDebtRatio(account, group, caseClientVO));
}

报错具体指向该行代码:

when(account.getAccountOwners()).thenReturn(List.of((new AccountOwnerVO(null, "199406208123", null))));
原因分析

这种仅在随机测试顺序下触发的失败,核心原因是测试用例之间的全局状态/静态资源污染:

  • 若AccountOwnerVO类包含静态字段、静态初始化逻辑,或依赖了全局配置,其他测试用例可能修改了这些状态,导致当前测试中创建的AccountOwnerVO实例不符合预期。
  • 测试类中存在类级别的共享Mock实例或变量(比如caseClientVO如果是类成员而非方法局部变量),随机顺序下前一个测试的修改会残留到当前测试中。
  • Mock框架(如Mockito)的全局配置被其他测试改动,或未正确重置Mock状态,导致when(...)的Stubbing行为失效。
修复方案
  1. 隔离测试依赖:确保所有测试用例的Mock对象、测试数据都是方法级局部变量,避免使用类级静态成员。比如caseClientVO如果是共享变量,改为在测试方法内初始化。
  2. 重置Mock状态:使用JUnit的@BeforeEach在每个测试前创建新的Mock实例,或用@AfterEach调用Mockito.reset()清除Mock的Stubbing记录。示例:
    @BeforeEach
    void setUp() {
        account = mock(AccountVO.class);
        group = mock(CustomerGroupInformationVO.class);
        caseClientVO = new CaseClientVO(...); // 每次测试初始化新实例
    }
    
  3. 检查全局状态:排查AccountOwnerVO及相关依赖类的静态字段,若存在可变静态状态,在每个测试后重置(比如添加静态重置方法,在@AfterEach中调用)。
  4. 启用严格Mock模式:给测试类添加@MockitoSettings(strictness = Strictness.STRICT_STUBS),强制检查未声明的Mock调用,快速定位状态污染引发的异常。
  5. 独立初始化测试数据:确保List.of(new AccountOwnerVO(...))这类测试数据在每个测试方法内独立创建,避免复用外部共享的集合实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:45:38