← Back to libraryQuestion 279 of 468
🔬TestNG & JUnitBeginner

Timeouts

📌 Definition:

A timeout fails a test if it runs longer than a limit, catching hangs/infinite loops and enforcing performance expectations. TestNG uses @Test(timeOut = ms); JUnit 5 uses @Timeout or assertTimeout.

📖 Detailed Explanation:

TestNG @Test(timeOut = 2000) fails the test if it exceeds 2000 ms (and works with dataProviders/invocationCount). JUnit 5: @Timeout(value = 2, unit = SECONDS) on a method, or assertTimeout(Duration.ofSeconds(2), () -> ...) (runs and then checks) vs assertTimeoutPreemptively (aborts when exceeded). Timeouts prevent a single hung test from stalling the whole suite/CI and can assert an operation meets an SLA. Be cautious with tight timeouts on machine-variable operations (network) to avoid flakiness — set generous, realistic limits.

🔑 Key Points:
  • TestNG @Test(timeOut=ms) fails if the test exceeds it
  • JUnit5 @Timeout / assertTimeout / assertTimeoutPreemptively
  • Catches hangs/infinite loops; can enforce an SLA
  • Avoid overly-tight timeouts on variable operations (flakiness)
🌍 Real-World Example:

A DB query test uses @Test(timeOut = 3000) so a query regression that makes it hang doesn't freeze CI — the test fails fast at 3 seconds with a clear timeout error.

🎯 Scenario-Based Interview Question:

A single test occasionally hangs and blocks the whole CI pipeline. How do timeouts help, and what's the flakiness caveat?