jeudi 28 janvier 2021

Testing surrounding try catch method with mockito

Im figuring out, how to test this method and force the exception "DataAccessResourceFailureException", but i didn't have a valid way to do it.

I need to force that exception at "ProductRepositoryImpl" class. Any ideas?

ProductRepositoryImpl

  @Override
  public Product saveProduct(Product input) {
  try {
    return productRepositoryAdapter.saveProduct(input);
  } catch (DataAccessResourceFailureException e) {
    logger.error(ERROR_WHEN_SAVING_PRODUCT_DATA_DETAIL + e.getMessage());
  }
    return null;
  }

ProductRepositoryAdapter

  public Product saveProduct(Product input) throws DataAccessResourceFailureException {
    ProductData productData = UtilTransform.productToProductData(input);

    // This method throws exception when there's no connection
    Product createdProduct = productDataRepository.findSkuByCountry(input.getSku(), 
    input.getCountry());

    if (createdProduct == null) {
       return Product.fromModel(productDataRepository.save(productData));
    } else {
      logger.error(THE_PRODUCT_ALREADY_EXISTS_IN_THE_RECORDS);
    }
      return null;
  }

ProductDataRepository

public interface ProductDataRepository extends MongoRepository<ProductData, String> {

  @Query("{'sku': ?0, 'country': ?1}")
  public Product findSkuByCountry(String sku, String country);

  public Optional<ProductData> findById(ProductId id);
}

And my Test, Im using mockito.

@Test
void saveProductException() {
  Mockito.when(productRepository.saveProduct(buildProduct())).thenReturn(buildProduct());
  Mockito.when(adapter.saveProduct(buildProduct())).
      thenThrow(DataAccessResourceFailureException.class);

  Assertions.assertThrows(DataAccessResourceFailureException.class, 
  () -> productRepository.saveProduct(buildProduct()));
}

Error:

org.opentest4j.AssertionFailedError: Expected org.springframework.dao.DataAccessResourceFailureException to be thrown, but nothing was thrown.

Aucun commentaire:

Enregistrer un commentaire