首页 > 解决方案 > 如何使用 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);
  }

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

标签: javajunit

解决方案


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

  1. id 是现有产品的,并且调用 imageRepository 来更新产品图像
  2. 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);
  });
}


}

推荐阅读