Test Overview
This test runs a simple method multiple times to detect if it sometimes fails unpredictably, which indicates a flaky test.
This test runs a simple method multiple times to detect if it sometimes fails unpredictably, which indicates a flaky test.
import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Assertions; import java.util.Random; public class FlakyTestDetection { private boolean sometimesFails() { // Simulate flaky behavior: fails randomly 30% of the time return new Random().nextInt(10) >= 7; } @RepeatedTest(10) void testSometimesFails() { Assertions.assertTrue(sometimesFails(), "Method failed unexpectedly"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and prepares to run testSometimesFails 10 times | JUnit test environment initialized | — | PASS |
| 2 | Runs testSometimesFails iteration 1: calls sometimesFails() | sometimesFails returns true (success) | assertTrue passes | PASS |
| 3 | Runs testSometimesFails iteration 2: calls sometimesFails() | sometimesFails returns true (success) | assertTrue passes | PASS |
| 4 | Runs testSometimesFails iteration 3: calls sometimesFails() | sometimesFails returns false (failure) | assertTrue fails with message 'Method failed unexpectedly' | FAIL |
| 5 | Test runner records failure for iteration 3 | Test report marks iteration 3 as failed | — | PASS |
| 6 | Runs testSometimesFails iteration 4 to 10: calls sometimesFails() | sometimesFails returns true for most, possibly false for some | assertTrue passes or fails accordingly | PASS OR FAIL DEPENDING ON ITERATION |
| 7 | Test runner finishes all 10 iterations and aggregates results | Test report shows some iterations passed, some failed | Overall test marked as flaky due to intermittent failures | FAIL |
What is a flaky test in JUnit?
Which JUnit feature helps detect flaky tests by rerunning failed tests automatically?
Consider this JUnit test snippet using a retry rule to detect flaky tests:
public class FlakyTest {
private int runCount = 0;
@Rule
public RetryRule retryRule = new RetryRule(3);
@Test
public void testFlaky() {
runCount++;
assertTrue(runCount >= 2);
}
}What will be the test result when run?
Identify the problem in this JUnit test intended to detect flaky tests by retrying:
@Rule
public RetryRule retryRule = new RetryRule(3);
@Test
public void testFlaky() {
int count = 0;
count++;
assertTrue(count > 1);
}You want to detect flaky tests in your JUnit suite by running each test 5 times and marking it flaky if it fails at least once. Which approach is best?
Pass the test and this pattern moves unknown