JUnit lets you enforce a maximum execution time for a test so it fails automatically if it hangs or runs too long, rather than blocking the test suite indefinitely.
Wrapping a call to a recursive algorithm suspected of an infinite loop bug with @Timeout(1) on the test method ensures the test suite fails fast instead of hanging forever.
@Test
@Timeout(1)
void completesQuickly() {
assertEquals(120, factorialCalculator.of(5));
}A concise interview answer is
In JUnit 4 I'd use @Test(timeout = 1000) to fail a test that runs longer than a second; in JUnit 5 I use @Timeout or assertTimeout(). It's how I guard against hangs or infinite loops so a broken test fails fast instead of blocking the whole suite.
Last updated: 16 July 2026
Previous question: What is a test suite in JUnit, and how do you create it?
Next question: How do you structure a test case in JUnit?