【发布时间】: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