vehk
vehk

Reputation: 107

How to test Service Layer with JPA Repos

I have s service methos which i want to test:

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

So to be able to call service method, i need to mock imageRepository somehow:

@Test
  void updateProductImage() {
    when(imageRepository)
        .updateProductImage(1L, imageAsStream).thenReturn(???);

    productService.updateProductImage(1L, imageAsStream);
  }

Can you please advise whats the general approach in such cases?

Upvotes: 1

Views: 169

Answers (1)

Wim Deblauwe
Wim Deblauwe

Reputation: 26878

When I would need to test this method, then these things need to be validated:

  1. The id is of an existing product and there is a call to the imageRepository to update the product image
  2. The id is not of an existing product. An exception is thrown and nothing is saved in the imageRepository

For your question, it does not really matter what you return there. It can be a mock of Product, or it can be a real instance.

My preference is usually to have an Object Mother, for example ProductMother to create a "default" instance.

In code:

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


}

Upvotes: 1

Related Questions