Introduction
This article will show how to set the maximum time a test can run. It is helpful for cases where you want to test if a method does not run too long.
Junit 5 Timeout examples
You can use the @Timeout
annotation if you are using Junit5. The annotation takes a Long as default, which is the number of seconds a test may take. However, it is also possible to pass a unit of time to the @Timeout
annotation; this makes it clear to the reader how long a test is allowed to run.
In the following example, you can see both ways of using the @Timeout
annotation.
|
|
Setting a timeout for every test inside a class
When you apply the @Timeout
annotation at the class level, the timeout will be set for every test inside the class.
|
|
Using Assertions
You can also use Assertions to ensure a method runs within a time limit. In the following example, we use Assertions.assertTimeout
.
This method has a parameter for the Duration and a Lambda, which has to finish within the given duration.
|
|
Junit 4 Timeout examples
If you are using Junit 4, you can't use the @Timeout
annotation, but there are other ways to set the timeout on a test method.
Using the @Test annotation
With Junit 4, you pass the number of milliseconds a test can run directly to the @Test
annotation.
In the following example, the test will timeout after 10 milliseconds.
|
|
Using a Rule
If you want to apply a timeout to all your tests in a class, you can use a @Rule
. In the following example, we set a timeout
of 20 milliseconds for each test inside the class.
|
|
@Test(timeout = 10)
timeout value inside the annotations will be ignored when used with an @Rule
. Instead, the timeout from the @Rule will be used.
Conclusion
In the article, we saw how we could set a timeout on a test and at the class level. We did this for JUnit 5 and 4.
Further reading
More about testing in Java: