如何使用 JPA Repos 测试服务层

How to test Service Layer with JPA Repos

我有 s 个服务方法要测试:

@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. 该 id 是现有产品的,调用 imageRepository 来更新产品图像
  2. 该 ID 不是现有产品。抛出异常,imageRepository
  3. 中没有保存任何内容

对于您的问题,return 那里的内容并不重要。它可以是 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);
  });
}


}