If the сook method ultimately works out correctly, then it should output something. So, how to check in the JUnit test that the cook method added?

 public String tasteToString() { switch(taste) { case SWEET: return "Sweet"; case SOUR: return "Sour"; case SALTY: return "Salty"; case BITTER: return "Bitter"; } return "Tasteless"; public void cook (List<Food> foods, String name, Veget veget) { int rand = new Random().nextInt(4); Food f = new Food(name); switch (rand) { case 0: f.setTaste(Taste.SWEET); break; case 1: f.setTaste(Taste.SOUR); break; case 2: f.setTaste(Taste.SALTY); break; case 3: f.setTaste(Taste.BITTER); break; } f.setVeget(veget); foods.add(f); } 
  • For the test you need a non- random random number generator. - Igor
  • Yes, since I’m having a rand here, I can’t verify what he will add SPECIFICALLY, because I do not know in advance what he will add, but I think you can check that he even added something at all (no matter what). - kompil 6:38 pm
  • one
    everything is simple, we compare the number of elements of the sheet, before the method is called, with the number of elements after the call - keekkenen

1 answer 1

In order to test such a method, you need to take out new Random() from it, otherwise the test will be incorrect, for example, if you don’t have to add to the list in one of the execution branches, you will stumble upon it with a certain probability in the test. This is not true. Such a test is worse than no test.

java sandbox

Kitchen.java

 import java.util.List; class Food { private Taste taste; private Veget veget; public Food(String name) {} public void setTaste(Taste taste) { this.taste = taste; } public void setVeget(Veget veget) { this.veget = veget; } public Taste getTaste() { return taste; } } enum Veget{ PEPPER } enum Taste { SWEET, SOUR, SALTY, BITTER } class Kitchen{ IRandom randomGenerator; public Kitchen(IRandom randomGenerator){ this.randomGenerator = randomGenerator; } public void cook(List<Food> foods, String name, Veget veget) { int rand = randomGenerator.nextInt(4); Food f = new Food(name); switch (rand) { case 0: f.setTaste(Taste.SWEET); break; case 1: f.setTaste(Taste.SOUR); break; case 2: f.setTaste(Taste.SALTY); break; case 3: f.setTaste(Taste.BITTER); break; } f.setVeget(veget); foods.add(f); } } interface IRandom { int nextInt(int i); } 

KitchenTest.java

 import org.junit.Test; import java.util.ArrayList; import java.util.List; public class KitchenTest { @Test public void cook() throws Exception { IRandom randomMock = new IRandom() { @Override public int nextInt(int i) { return 0; } }; List<Food> foods = new ArrayList<Food>(); Kitchen k = new Kitchen(randomMock); k.cook(foods, "a", Veget.PEPPER); org.junit.Assert.assertEquals(foods.get(0).getTaste(), Taste.SWEET); } }