Time Testing with Java JUnit assertTimeout method


At times when writing unit test cases for your Java project, you may want to fail a test based on the time a particular code takes to execute. For such cases, you can make use of the Junit assertTimeout static method from org.junit.jupiter.api.Assertions.

Below is a simple example, where we have a BusinessLogic class with a method complexCalculation that should complete within 10 seconds or else the unit test should fail.


Example:
package org.example;

public class BusinessLogic {

    public void complexCalculation() throws InterruptedException {

        //Some code that should complete
        // in 10 seconds
        Thread.sleep(12000);

    }
}
import org.example.BusinessLogic;
import org.junit.jupiter.api.Test;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertTimeout;

public class BusinessLogicTest {
    @Test
    public void testComplexCalculationExecutionTime() {
        BusinessLogic businessLogic = new BusinessLogic();

        assertTimeout(Duration.ofSeconds(10), () -> {
            businessLogic.complexCalculation();
        });
    }
}
org.opentest4j.AssertionFailedError: execution exceeded timeout of 10000 ms by 2004 ms

	at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152)
	at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
	at org.junit.jupiter.api.AssertTimeout.assertTimeout(AssertTimeout.java:81)
        ...
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap