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();
});
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!