0
0
JUnittesting~15 mins

Deterministic tests in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that the random number generator produces the same sequence with a fixed seed
Preconditions (2)
Step 1: Create a Random object with seed 12345
Step 2: Generate 5 random integers using nextInt()
Step 3: Record the generated numbers
Step 4: Create another Random object with the same seed 12345
Step 5: Generate 5 random integers again
Step 6: Compare both sequences of numbers
✅ Expected Result: Both sequences of 5 random integers are exactly the same, proving the test is deterministic
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the two sequences of random numbers are equal
Best Practices:
Use fixed seed for Random to ensure deterministic output
Use assertArrayEquals or assertEquals for comparing sequences
Keep test isolated and repeatable
Use descriptive test method names
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Random;
import org.junit.jupiter.api.Test;

public class DeterministicRandomTest {

    @Test
    void testRandomSequenceIsDeterministic() {
        int seed = 12345;
        Random random1 = new Random(seed);
        int[] sequence1 = new int[5];
        for (int i = 0; i < 5; i++) {
            sequence1[i] = random1.nextInt();
        }

        Random random2 = new Random(seed);
        int[] sequence2 = new int[5];
        for (int i = 0; i < 5; i++) {
            sequence2[i] = random2.nextInt();
        }

        assertArrayEquals(sequence1, sequence2, "Random sequences should be identical with the same seed");
    }
}

This test creates two Random objects with the same fixed seed (12345). Because the seed is fixed, the sequence of numbers generated by both Random instances will be the same.

We generate 5 integers from each Random object and store them in arrays. Then we use assertArrayEquals to verify both arrays are identical.

This ensures the test is deterministic, meaning it will always produce the same result every time it runs, which is important for reliable automated tests.

The test method is annotated with @Test from JUnit 5, and the code uses clear variable names and comments to keep it easy to understand.

Common Mistakes - 3 Pitfalls
Not using a fixed seed for the Random object
Comparing random numbers one by one with separate assertions
Using System.out.println for verification instead of assertions
Bonus Challenge

Now add data-driven testing with 3 different seeds to verify deterministic sequences for each seed

Show Hint