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