Search code examples
javajunitmockito

How to mock local arraylist in method


Im trying to make an unit test for this method

 public void loadProductsFromAPI() {

        List<ProductEntity> databaseProducts = productService.getAllProductsFromBd();
        CountryTenant.country.forEach((key, value) -> {

            List<ProductEntity> productsByCountry = databaseProducts.stream()
                    .filter(product -> key.toString().equalsIgnoreCase(product.getCountry()))
                    .collect(Collectors.toList());

            List<ProductDTO> productsFromAPI = productsApi.getAllProductsFromAPI(value);
            List<ProductEntity> processedProducts = productService.persistProductsFromApi(key, productsByCountry, productsFromAPI);
        });

}

My problem its the List<ProcuctEntity> productsByCountry, that variable is created in the execution time. How can I mock that in my test case?

With mockito I already mock my products from db.

Mockito.when(productService.getAllProductsFromBd()).thenReturn(databaseProducts);

Solution

  • If you ever find yourself trying to mock a value, you probably need to clean up your test plan. In this case, the productsByCountry is a value that is calculated inside your method: The correctness of that stream pipeline is part of what you need to verify. Mocking it would simply bypass ensuring that your logic is correct.

    Instead, return appropriate test data from the mock productService and ensure that the correct filtered result if passed to persistProducts.