【发布时间】:2020-10-11 06:30:07
【问题描述】:
我有一个从JpaRepository 扩展的实现接口
当我使用repository.existById();
并在数据库中传递不可用的 id。
它返回NullPointerException,文档中没有提到NullPointer。
这是一个布尔值,为什么它返回NullPointerException?
我的仓库
@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {
Boolean existsAccountByClientUsername(String username);
Account findAccountByClientUsername(String username);
}
使用 exsistByID 的测试代码
@Test
public void givenNotAvailableId_whenGetAccountById_thenThrowIllegalArgumentException() {
Long id = Long.MAX_VALUE;
IllegalArgumentException exception = Assertions
.assertThrows(IllegalArgumentException.class, () -> accountService.getAccountById(id));
Assertions.assertEquals("Id not found", exception.getMessage());
}
生产代码
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public Optional<Account> getAccountById(Long id) {
throwIfNotFoundId(id);
return accountRepository.findById(id);
}
}
throwIfNotFoundId 方法
private void throwIfNotFoundId(Long id) {
if (!accountRepository.existsById(id)) {
throw new IllegalArgumentException("Id not found");
}
}
【问题讨论】:
-
在帖子中为您的错误添加完整的堆栈跟踪
-
还添加更多关于您的测试代码的信息
标签: java spring spring-boot unit-testing repository