mardi 24 octobre 2023

How do I test code with randomized Input in Java

I'm writing a Yahtzee-style game and I'm in the stage where I've finished coding the ResultCalculator class, which takes the combination of dice and calculates, which results (Large Straight, Yahtzee...) are valid results.

I can't figure out a good way to test it, since the input is randomized. Sure, I could manipulate the Draw class where the dice are rolled so that I can manually set the dies' values but that doesn't seem very straightforward. Any ideas? How are classes like this getting tested in real life?

public class Die {
    private Value value;
    private int valueAsInt;
    private final Random random = new Random();

    public void rollDie() {
        int result = random.nextInt(1, 7);
        value = switch (result) {
            case 1 -> Value.ONE;
            case 2 -> Value.TWO;
            case 3 -> Value.THREE;
            case 4 -> Value.FOUR;
            case 5 -> Value.FIVE;
            case 6 -> Value.SIX;
        };
        valueAsInt = result;
    }


public class Draw {
    private static final int NUMBER_OF_DICE = 5;
    private final Die[] dice = new Die[NUMBER_OF_DICE];
    private final ArrayList<Integer> dieValuesAsInt = new ArrayList<>();
    private ArrayList<Result> results = new ArrayList<>();

 
    private void rollDice() {
        for (Die die : dice) {
            die.rollDie();
        }
    }


Then a ResultCalculator is called, it gets handed over Draw.dice & Draw.dieValuesAsInt




Aucun commentaire:

Enregistrer un commentaire