Nov 1, 2018

How to Add a Timeout for Execution in JUnit

Execution Timeout in JUnit

It is frequently useful to be able to kill a test that is taking too long to execute. Unexpected stalls, for example, can turn quick runs of unit tests into long-lasting affairs. The @Test annotation offers the timeout attribute, which specifies a time that, if exceeded, causes a test method to fail. The timeout attribute uses milliseconds.

A time limit applied to all tests in a test class is a common need, and JUnit offers the Timeout rule class to handle this. It can use units of seconds or milliseconds. The following defines a global timeout rule with five seconds and a test method that never finishes.
public class LongRunningTests {

    @Rule
    public Timeout globalTimeout = Timeout.seconds(5);

    @Test
    public void whatWeDoInATestMethodEchoesInEternity() {
        while (true);
    }
}
An excerpt will be thrown after five seconds of execution of the test.