java - 如何使用 JPA Repos 测试服务层
问题描述
我有我想测试的服务方法:
@Override
public void updateImage(long id, ImageAsStream imageAsStream) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ProductException("Product can not be found"));
updateProductImage(imageAsStream, product.getImage().getId());
}
private void updateProductImage(ImageAsStream imageAsStream, Long existingImageId) {
imageRepository.updateProductImage(existingImageId, imageAsStream);
imageRepository.copyImageToThumbnail(existingImageId);
}
所以为了能够调用服务方法,我需要以某种方式模拟 imageRepository:
@Test
void updateProductImage() {
when(imageRepository)
.updateProductImage(1L, imageAsStream).thenReturn(???);
productService.updateProductImage(1L, imageAsStream);
}
您能否告知在这种情况下的一般方法是什么?
解决方案
当我需要测试此方法时,需要验证以下内容:
- id 是现有产品的,并且调用 imageRepository 来更新产品图像
- id 不是现有产品。抛出异常,imageRepository 中没有保存任何内容
对于您的问题,您返回那里并不重要。它可以是 的模拟Product
,也可以是真实的实例。
我的偏好通常是拥有一个Object Mother,例如ProductMother
创建一个“默认”实例。
在代码中:
class ProductServiceTest {
@Test
void testHappyFlow() {
ProductRepository repository = mock(ProductRepository.class);
ProductService service = new ProductService(repository);
when(repository.findById(1L))
.thenReturn(ProductMother.createDefaultProduct());
ImageAsStream imageAsStream = mock(ImageAsStream.class);
service.updateImage(1L, imageAsStream);
verify(repository).updateProductImage(1L, imageAsStream);
verify(repository).copyImageToThumbnail(1L);
}
@Test
void testProductNotFound() {
ProductRepository repository = mock(ProductRepository.class);
ProductService service = new ProductService(repository);
assertThatExceptionOfType(ProductException.class)
.isThrownBy( () -> {
ImageAsStream imageAsStream = mock(ImageAsStream.class);
service.updateImage(1L, imageAsStream);
});
}
}
推荐阅读
- php - 当我设置测试的 setUp 方法时,没有结果
- batch-file - WiX 自定义操作 SetProperty 的命令行参数语法
- python - 使用 SPACY 的句子中第一个单词的 POS 计数
- c++ - 使用 C++ 在文本文件中修改
- java - Java - 如何在同一行中读取具有 Int 和字符串的文本文件
- java - Sqlite:更新查询不会将值更新到数据库
- python - 裁剪和存储图像集合的边界框图像区域?
- c++ - cout 输出不是从左到右吗?
- sql-server - SQL Server CASE,选择表列
- javascript - Github 页面未显示网站内容和错误 404