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

Spring Boot项目中Repository的findById方法Junit测试不通过求助

问题原因

  • 错误使用Mockito参数匹配器赋值:anyInt()是Mockito用于方法Stub时的参数匹配工具,不能用作普通变量赋值,虽然此处不会直接导致报错,但属于不规范用法。
  • 未触发待测试方法执行:你仅完成了Repository层的Mock配置和异常预期声明,完全没有调用DefaultQuarterService的findById方法,自然不会抛出预期异常,是本次测试失败的核心原因。
  • 缺少Service实例配置:测试类中仅声明了Mock的Repository,没有将其注入到待测试的DefaultQuarterService实例中,无法执行Service层方法。

修复方案

轻量Mockito单元测试方案(无需加载Spring上下文,执行速度更快)

JUnit 4 版本

@RunWith(MockitoJUnitRunner.class)
public class QuarterServiceTest {

    @Rule
    public ExpectedException expectException = ExpectedException.none();

    @Mock
    private QuarterRepository quarterRepository;

    @InjectMocks
    private DefaultQuarterService quarterService;

    @Test
    public void throwExceptionWhenQuarterIdNotFound() {
        int testId = 1;
        // 配置Mock Repository返回空
        when(quarterRepository.findById(testId)).thenReturn(Optional.empty());
        // 声明预期异常
        expectException.expect(EntityNotFoundException.class);
        expectException.expectMessage(String.format("Quarter does not exist for id = %s!", testId));
        // 调用待测试方法,触发异常
        quarterService.findById(testId);
    }
}

JUnit 5 版本

JUnit5已废弃ExpectedException,推荐使用assertThrows实现更简洁的异常测试:

@ExtendWith(MockitoExtension.class)
public class QuarterServiceTest {

    @Mock
    private QuarterRepository quarterRepository;

    @InjectMocks
    private DefaultQuarterService quarterService;

    @Test
    public void throwExceptionWhenQuarterIdNotFound() {
        int testId = 1;
        when(quarterRepository.findById(testId)).thenReturn(Optional.empty());
        
        // 断言执行方法时抛出指定异常
        EntityNotFoundException exception = org.junit.jupiter.api.Assertions.assertThrows(
                EntityNotFoundException.class,
                () -> quarterService.findById(testId)
        );
        // 校验异常信息是否符合预期
        org.junit.jupiter.api.Assertions.assertEquals(
                String.format("Quarter does not exist for id = %s!", testId),
                exception.getMessage()
        );
    }
}

Spring Boot集成测试方案

如果需要加载Spring上下文,仅需调整Bean注入方式即可,逻辑和上述代码一致:

  • 把@Mock替换为@MockBean
  • 把@InjectMocks替换为@Autowired
  • 测试类增加@SpringBootTest注解

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:57:04