【问题标题】:Junit Test: findById method of the RepositoryJunit 测试:Repository 的 findById 方法
【发布时间】:2021-11-16 00:01:01
【问题描述】:

我是 Junit 测试的新手,对此我有疑问。在这里您可以在我的服务类中看到 findById 方法:

@Service
public class DefaultQuarterService implements QuarterService {

    private final QuarterRepository quarterRepository;

    public DefaultQuarterService(QuarterRepository quarterRepository) {
        this.quarterRepository = quarterRepository;
    }

    @Override
    public QuarterEntity findById(int id) {

        return quarterRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException(String.format("Quarter does not exist for id = %s!", id)));
    }
}

这是我的 QuarterRepository:

@Repository
public interface QuarterRepository extends CrudRepository<QuarterEntity, Integer> {
}

这是我对这个方法的 Junit 实现:

@MockBean
private QuarterRepository quarterRepository;

@Test
public void throwExceptionWhenQuarterIdNotFound() {
    int id = anyInt();
    when(quarterRepository.findById(id))
            .thenReturn(Optional.empty());
    assertThatAnExceptionWasThrown(String.format("Quarter does not exist for id = %s!", id));
}

public void assertThatAnExceptionWasThrown(
        String errorMsg
) {
    expectException.expect(RuntimeException.class);
    expectException.expectMessage(errorMsg);
}

不幸的是,测试没有通过。这是终端中的错误:

java.lang.AssertionError:预期的测试抛出(一个实例 java.lang.RuntimeException 和带有消息字符串的异常 包含“id = 0 的季度不存在!”)

也许它是如此简单,但我看不出我错过了什么。如果你能指导我,我会很高兴。非常感谢!

【问题讨论】:

  • “在这里您可以看到我在服务类中从 CrudRepository findById 覆盖的方法” - 您的服务类是否实现了 CrudRepository?你能分享一下你是如何声明你的服务类的吗?
  • @6ton 感谢您的评论。问题已更新!

标签: java spring-boot unit-testing junit spring-test


【解决方案1】:

第一期

assertThatAnExceptionWasThrown 方法中,您期望RuntimeException 但是 在您抛出EntityNotFoundException 的服务类中,所以我想您应该在测试用例中期望EntityNotFoundException

第二期

在这部分代码之后。

 when(quarterRepository.findById(id))
            .thenReturn(Optional.empty());

你为什么不调用你的服务方法(findById)? 当您返回空值时,您应该使用要测试的服务方法验证您的条件。 应该是这样的。

assertThatThrownBy(() -> defaultQuarterService.findById(id))
        .isInstanceOf(ApiRequestException.class)
        .hasMessageContaining("PUT_YOUR_EXCEPTION_MESSAGE_HERE");

这是在 Spring Boot 中进行单元测试的一个很好的示例。你可以检查一下。 Link

尝试上述解决方案,让我知道它是否已修复。祝你好运

【讨论】:

  • 您好!你的建议真的很有帮助。我没有按照您的建议添加带有 assertThatThrownBy() 的部分,但我在 assertThatAnExceptionWasThrown 函数调用之后添加了: QuarterService.findById(id) 。现在它通过了测试!非常感谢!
【解决方案2】:

当您模拟您的存储库时,它将正确返回Optional.empty(),我认为您应该调用您的服务(即自动接线)findById 方法。它实际上会抛出异常。

【讨论】:

  • 嗨 @zip88 我在 assertThatAnExceptionWasThrown 函数调用之后添加了: QuarterService.findById(id) 。现在它通过了测试!非常感谢!
猜你喜欢
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多