How do you mock behavior for methods that depend on randomness (like Math.random())?

Testing code that depends on randomness, like Math.random(), requires isolating the random source behind an interface so it can be mocked and given deterministic values in tests.

Key Points

Example

A DiceRoller class calling Math.random() internally is hard to test; extracting a RandomSource.nextDouble() dependency lets a test stub it to return exactly 0.5 and assert the resulting roll is deterministic.

interface RandomSource {
    double nextDouble();
}

class DiceRoller {
    private final RandomSource random;
    DiceRoller(RandomSource random) { this.random = random; }
    int roll() { return (int) (random.nextDouble() * 6) + 1; }
}

@Test
void rollsPredictableValue() {
    RandomSource random = mock(RandomSource.class);
    when(random.nextDouble()).thenReturn(0.0);

    assertEquals(1, new DiceRoller(random).roll());
}

Interview Tip

A concise interview answer is

I abstract the random source behind a small interface, inject it into the class under test, and mock that interface to return a fixed value with when()/thenReturn(). That turns an inherently nondeterministic method into something I can assert on precisely.

Last updated: 16 July 2026

Previous question: Can you explain Mockito's RETURNS_DEEP_STUBS and its use case?

Next question: How do you combine JUnit and Mockito to write comprehensive unit tests?

More Mockito interview questions

All Mockito questions