如何使用 JPA Repos 测试服务层

时间:2021-06-29 02:08:02

标签: java junit

我有要测试的服务方法:

@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);
  }

您能否告知在这种情况下的一般方法是什么?

1 个答案:

答案 0 :(得分:1)

当我需要测试此方法时,需要验证以下内容:

  1. 该 ID 属于现有产品,并且调用了 imageRepository 以更新产品图像
  2. 该 ID 不是现有产品的 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);
  });
}


}