HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Junit / JUnit Test Timeout – JUnit 5 Timeout Example

JUnit Test Timeout – JUnit 5 Timeout Example

Learn to write JUnit tests with timeout behavior. If any test does not complete execution in given time limit then it’s execution will stop by JUnit. Also learn to use JUnit 5 test timeout using assertions.

1. Why to write JUnit timeout tests?

Sometimes, we have to write JUnit tests where we have to access some external systems on network. This is never 100% certainty that these external systems will be available while executing the test cases. That’s why it is advisable to use timeout property of JUnit framework while writing test cases with external dependencies.

This is also considered JUnit best practice to be followed.

Each JUnit test is run in a new thread. If the specified timeout elapses before the test completes, its execution is interrupted via Thread.interrupt().

2. JUnit test timeout example – ‘timeout’ attribute

To specify timeout period of a certain test case, “timeout” attribute is mentioned on annotation @Test. For example, @Test(timeout = 1000).

Timeout time is specified in milliseconds.

@Test(timeout = 500)
public void testInfiniteTametakingLoop() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(1000);
	}
}

In above test, execution will timeout after 5 seconds with below message.

java.lang.Exception: test timed out after 5000 milliseconds

2. JUnit global timeout example – Timeout Rule

Rather than specifying timeout attribute for all tests separately, we can define JUnit Rule for all tests in a class.

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

@Test 	//Pass
public void testInfiniteTametakingLoop1() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(1000);
	}
}

@Test 	//Fail
public void testInfiniteTametakingLoop2() throws InterruptedException 
{
	while (true)
	{
		Thread.currentThread().sleep(5000);
	}
}

In above example, first test will pass while second test will fail.

Please note that above timeout @Rule applies on @Before and @After methods as well. So use it carefully.

4. JUnit 5 timeout using assertion

In JUnit 5, we can force timeout of tests using assertions.

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

@Test
void timeoutNotExceeded() 
{
    //The following assertion succeeds.
    assertTimeout(ofMinutes(2), () -> {
        // Perform task that takes less than 2 minutes.
    });
}

@Test
void timeoutExceeded() 
{
    // The following assertion fails with an error message similar to:
    // execution exceeded timeout of 10 ms by 91 ms
    assertTimeout(ofMillis(10), () -> {
        // Simulate task that takes more than 10 ms.
        Thread.sleep(100);
    });
}

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

JUnit 5 Tutorial

  • JUnit 5 – Introduction
  • JUnit 5 – Test LifeCycle
  • JUnit 5 – @BeforeAll
  • JUnit 5 – @BeforeEach
  • JUnit 5 – @AfterEach
  • JUnit 5 – @AfterAll
  • JUnit 5 – @RepeatedTest
  • JUnit 5 – @Disabled
  • JUnit 5 – @Tag
  • JUnit 5 – Expected Exception
  • JUnit 5 – Assertions Examples
  • JUnit 5 – Assumptions
  • JUnit 5 – Test Suites
  • JUnit 5 – Gradle Dependency
  • JUnit 5 – Maven Dependency
  • JUnit 5 – Execute Test in Eclipse
  • JUnit 5 – Eclipse Test Templates
  • JUnit 5 vs JUnit 4

JUnit 4 Tutorial

  • JUnit – Introduction
  • JUnit – Test Suite
  • JUnit – Execute with JUnitCore
  • JUnit – Execute with Maven
  • JUnit – org.junit.Assume
  • JUnit – Expected Exceptions
  • JUnit – Listeners
  • JUnit – Force Timeout
  • JUnit – Ordered Tests
  • JUnit – Parameterized Tests
  • Junit – @Theory And @DataPoints
  • JUnit – TemporaryFolder @Rule

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)