Managing JUnit Test Timeout

If you want to ensure that a test fails if it isn’t done in a certain amount of time you can use the assertTimeout() method. This ensures that tests that take too long, can be automatically failed.

Here is an example

package com.example;

import static org.junit.Assert.assertEquals;

import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.assertTimeout;

import org.junit.jupiter.api.Test;


public class TimeAssertionOutExample {

    private static String greeting() {
        return "Hello";
    }
    // The following assertion succeeds.
    @Test
    void simpleTimeout() {

        assertTimeout(ofMinutes(1), () -> {
            // Perform task that takes less than 1 minute.
        });
    }

    @Test
    void simpleTimeoutWithResult() {
        // The following assertion succeeds, and returns the supplied object.
        String actualResult = assertTimeout(ofMinutes(1), () -> {
            return "a result";
        });
        assertEquals("a result", actualResult);
    }
    // The following assertion invokes a method reference and returns an object.
    @Test
    void simpleTimeoutWithMethod() {

        String actualGreeting = assertTimeout(ofMinutes(1), TimeAssertionOutExample::greeting);
        assertEquals("Hello", actualGreeting);
    }
    // The following assertion fails with an error message similar to:
    // execution exceeded timeout of 10 ms by 91 ms
    @Test
    void timeoutExceeded() {
        
        assertTimeout(ofMillis(10), () -> {
            Thread.sleep(100);
        });
    }
}

Include the following dependency to run the Testsuite class:

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <junit-platform.version>1.2.0</junit-platform.version>
    <junit-jupiter.version>5.2.0</junit-jupiter.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.junit.platform</groupId>
      <artifactId>junit-platform-runner</artifactId>
      <version>${junit-platform.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>${junit-jupiter.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <version>${junit-jupiter.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>${junit-jupiter.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>
Found the article helpful? if so please follow us on Socials