Testing / JUnit6 Interview Questions
What is the @RepeatedTest annotation in JUnit 6?
@RepeatedTest(n) runs a test method exactly n times. Each repetition is treated as an independent test. It is useful for verifying non-deterministic behaviour, testing concurrency, or stress-testing time-sensitive operations.
import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.RepetitionInfo; class RepeatedTestDemo { // Simple: run exactly 5 times @RepeatedTest(5) void repeatedTest() { assertTrue(Math.random() >= 0.0); } // Custom display name with placeholders: // {displayName}, {currentRepetition}, {totalRepetitions} @RepeatedTest( value = 5, name = "Repetition {currentRepetition} of {totalRepetitions}" ) void namedRepetitions() { // Runs 5 times with names: "Repetition 1 of 5", "Repetition 2 of 5"... } // Inject RepetitionInfo to know which repetition you are in: @RepeatedTest(3) void withRepetitionInfo(RepetitionInfo info) { System.out.printf("Running repetition %d of %d%n", info.getCurrentRepetition(), info.getTotalRepetitions()); // Common pattern: fail only on last repetition // to verify eventual consistency: if (info.getCurrentRepetition() == info.getTotalRepetitions()) { assertEquals("done", checkEventualState()); } } } // Common use cases for @RepeatedTest: // - Flaky test isolation (run 10x to catch intermittent failures) // - Cache warm-up tests (first invocation is slow, later are fast) // - Thread safety tests (repeated concurrent invocations) // - Eventual consistency checks (state converges by Nth repetition)
More Related questions...