How do you handle timeouts in JUnit?

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.

Key Points: • In JUnit 4, @Test(timeout = 1000) fails the test if it takes longer than 1000 milliseconds. • In JUnit 5, the equivalent is assertTimeout(Duration.ofMillis(1000), () -> { ... }) or the @Timeout annotation on a test method. • assertTimeoutPreemptively() in JUnit 5 actively interrupts the test's thread when the duration is exceeded, unlike assertTimeout() which lets it finish first. • Timeouts are useful for catching infinite loops, deadlocks, or unexpectedly slow I/O in code under test. • Overly strict timeouts on CI machines with variable performance can cause flaky test failures unrelated to real bugs.

Example: 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.

Code Example:

@Test
@Timeout(1)
void completesQuickly() {
    assertEquals(120, factorialCalculator.of(5));
}

Interview Tip: 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."