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.
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.
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.
A single test occasionally hangs and blocks the whole CI pipeline. How do timeouts help, and what's the flakiness caveat?