Why should you avoid conditional logic in unit tests and how?

Imagine the following classes:

public class Product {
   private String name;
   private double price;

   // Constructors, getters and setters
}

public class Products {
   private List<Product> products;

   // CRUD methods

   public double getTotalPrice() {
      // calculates the price of all products
   }
}

I read that in unit tests you should avoid conditional logic (if and loops), but it is not clear why and more importantly how. How can I effectively test the scenario when I add some products at Productsdifferent prices and then check the result getTotalPrice()without using loops?

+4
source share
2 answers

Fear with conventions and cycles is twofold:

  • You may have an error in the TEST code, so the test does not run properly or worse. The statement inside the conditional block is not approved.
  • .

. , , .

Invisible Arrow, :

@Test
public void testsTotalPriceAsSumOfProductPrices() {
    Products products = new Products(); // Or any appropriate constructor
    products.add(new Product("first", 10)); // Assuming such a constructor exists
    products.add(new Product("second", 20));
    products.add(new Product("second", 30));
    assertEquals("Sum must be eq to 60", 60, products.getTotalPrice());
}

Product , .

, (, ).

:

 @Test
public void testsTotalPriceAsSumOfProductPrices() {
    Products products = new Products(); 

    addProductsWithPrices(products, 10,20,30);

    assertEquals(60, products.getTotalPrice());

}

private static void addProductsWithPrices(Products products, Double...prices){
  for(Double price : prices){
     //could keep static counter or something
     //to make names unique
     products.add(new Product("name", price));
  }
}

, for. , , , ! , .

, , , (name), . , , , , . , , 10 + 20 + 30 == 60.

, - double - Currency, , .

 private static void addProductsWithPrices(Products products, Double...prices){
  for(Double price : prices){
     //could keep static counter or something
     //to make names unique
     products.add(new Product("name", Currency.valueOf(price)));
  }
}
+5

, . , , unit test. . , , , / .

, .

public class ProductsTest {
    @Test
    public void testsTotalPriceAsSumOfProductPrices() {
        Products products = new Products(); // Or any appropriate constructor
        products.add(new Product("first", 10)); // Assuming such a constructor exists
        products.add(new Product("second", 20));
        products.add(new Product("second", 30));
        assertEquals("Sum must be eq to 60", 60, products.getTotalPrice());
    }
}

, / .

, , , , ..

+1

Source: https://habr.com/ru/post/1570721/


All Articles