【发布时间】:2021-08-15 16:39:02
【问题描述】:
我有一个ProductService,它通过ProductRepository 查询数据库。在那里我有一个更新方法和一个查找方法。更新方法为updateProductInDatabase(String id, Product updateInfo)。 updateProductInDatabase 调用方法 findProductInDatabaseById(String id),该方法返回 Product 或抛出 ResourceNotFoundException。
我的代码:
public void updateProductInDatabase(String id, Product updateInfo) {
Product product = findProductInDatabaseById(id);
if (correctFormat(updateInfo.getVersion()) {
product.setVersion(updateInfo.getVersion());
repository.save(updateInfo);
//restOfTheCode
} else {
// Throws invalid input exception
}
}
private Products findProductInDatabaseById(String id) {
Optional<Product> productOptional =
repository.getAllProducts().stream.findFirst(); // return a list, but I only need the first
return productOptional.orElseThrow(...) // Throws resource not found exception
}
我想为此代码编写单元测试,该代码预期输入无效异常,但测试失败
意外异常:预期 InvalidInputException,但发现 ResourceNotFoundException
发生这种情况是因为 productOptional 始终是一个空的可选项。
有人可以帮助提供模拟 productOptional 的解决方法吗?
编辑:添加我的测试
@Test(expected = InvalidInputException.class)
public void testUpdateProductVersionInDatabaseWhenVersionIsIncorrectFormat()
throws ApiException {
Product product = new Product();
product.setVersion("error-version");
when(repository.getAllProducts())
.thenReturn(Collections.singletonList(new Product()));
productService.updateProductInDatabase("product-id-1", product);
}
【问题讨论】:
-
请分享一个测试
-
@YuriyTsarkov 我刚刚添加了测试
-
好吧,你抛出了一个
ResourceNotFoundException,但是InvalidInputException按预期放置了,那么有什么问题吗?将期望值更改为ResourceNotFoundException -
我不希望
ResourceNotFoundException被抛出,我希望服务在检查版本格式后抛出InvalidInputException -
您的代码没有多大意义。尤其是
findProductInDatabaseById: void 方法,它返回一些东西并且从不关心 ID。那么你能提供正确的代码吗?进一步:ResourceNotFoundException-> 这是您在orElseThrow中声明为供应商的自定义异常吗?