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

使用Junit、Mockito测试names长度<5时抛出异常的单元测试场景

测试实现方案

核心思路:你需要mock HelperService的addValues方法,拦截方法调用时传入的names列表,手动控制列表的元素数量即可实现场景模拟,完全不需要修改原有业务代码。

完整测试代码(JUnit 5 + Mockito 4.x+ 版本)

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.doAnswer;

@ExtendWith(MockitoExtension.class)
public class ExampleTest {

    @Mock
    private HelperService hs;

    @InjectMocks
    private Example example;

    @Test
    public void testSomeMethod_WhenNamesSizeLessThan5_ThrowRuntimeException() {
        // 拦截addValues方法,仅往传入的列表中添加2个元素,模拟长度不足5的场景
        doAnswer(invocation -> {
            List<String> names = invocation.getArgument(0);
            names.add("test1");
            names.add("test2");
            return null; // void方法返回null即可
        }).when(hs).addValues(anyList());

        // 验证方法调用会抛出预期异常
        assertThrows(RuntimeException.class, () -> example.someMethod(), "Invalid names list");
    }
}

关键逻辑说明

  • @Mock会创建HelperService的代理对象,@InjectMocks会自动将mock对象注入到Example实例的hs属性中,无需手动编写set方法
  • 针对void类型的mock方法,使用doAnswer进行调用拦截,通过invocation.getArgument(0)可以拿到someMethod内部传入的names列表实例,直接修改该实例的元素数量就能模拟出元素不足的场景
  • 如果你使用JUnit 4,只需要把测试类的注解换成@RunWith(MockitoJUnitRunner.class),断言方法换成JUnit 4对应的Assert.assertThrows或者ExpectedException规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:15:05