我有一个使用 Spring Data JPA 的 findById() 方法的方法应该返回一个 Optional。但是,如果指定的 id 找不到实体,它将返回 null 而不是 Empty Optional。
public TicketEntity findTicket(String ticket) throws EntityNotFoundException {
Optional<TicketEntity> op = ticketEntityRepository.findById(ticket);
TicketEntity ticketEntity = op.orElseThrow(() -> new EntityNotFoundException("ticket with the id " + ticket + " not found in the system"));
return ticketEntity;
}
调试时发现op的值为null。 这是失败的代码段。我正在使用 Spring Data JPA 2.0.8.RELEASE。请帮忙
最佳答案
在评论中,您声明这是在具有模拟依赖项的测试中。模拟将 Spring Data JPA 完全排除在外,因为它现在只是一个由来自 Mockito 的模拟实现的代理。 .
mock 的默认行为是返回 null
。
By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.
当您使用模拟运行时,您需要指示它返回一个 Optional.empty()
,否则您将得到 null
。
注意:您可能希望为 Mockito 创建一个改进请求,以便在 Optional
返回类型的情况下默认返回 Optional.empty
.
关于java - Spring Data JPA findById() 方法返回 null 而不是 Empty Optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058898/