0
0
JUnittesting~10 mins

Deterministic tests in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the test deterministic by fixing the seed.

JUnit
Random random = new Random([1]);
int value = random.nextInt(100);
assertEquals(42, value);
Drag options to blanks, or click blank then click option'
ASystem.currentTimeMillis()
Bnew Date().getTime()
C0
D12345
Attempts:
3 left
💡 Hint
Common Mistakes
Using time-based seeds like System.currentTimeMillis() causes non-deterministic tests.
2fill in blank
medium

Complete the code to assert the expected value in a deterministic test.

JUnit
@Test
public void testRandomValue() {
    Random random = new Random(0);
    int value = random.nextInt(100);
    assertEquals([1], value);
}
Drag options to blanks, or click blank then click option'
A50
B0
C99
D42
Attempts:
3 left
💡 Hint
Common Mistakes
Guessing the expected value without running the code causes assertion failures.
3fill in blank
hard

Fix the error in the test to make it deterministic by replacing the non-deterministic call.

JUnit
@Test
public void testTimestamp() {
    long fixedTimestamp = 1234567890L;
    long timestamp = [1];
    assertEquals(fixedTimestamp, timestamp);
}
Drag options to blanks, or click blank then click option'
Anew Date().getTime()
B1234567890L
CSystem.nanoTime()
DInstant.now().toEpochMilli()
Attempts:
3 left
💡 Hint
Common Mistakes
Using System.currentTimeMillis() or similar methods causes flaky tests.
4fill in blank
hard

Fill both blanks to create a deterministic test that checks a fixed random value.

JUnit
@Test
public void testFixedRandom() {
    Random random = new Random([1]);
    int value = random.nextInt([2]);
    assertEquals(42, value);
}
Drag options to blanks, or click blank then click option'
A0
B100
C50
DSystem.currentTimeMillis()
Attempts:
3 left
💡 Hint
Common Mistakes
Using dynamic values for seed or bound causes non-deterministic tests.
5fill in blank
hard

Fill all three blanks to create a deterministic test that asserts a fixed string length.

JUnit
@Test
public void testStringLength() {
    String text = "hello";
    int length = text.[1]();
    assertEquals([2], length);
    assertTrue(length [3] 0);
}
Drag options to blanks, or click blank then click option'
Alength
B5
C>
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using size() instead of length() causes compilation errors.