In this post under Junit, I will show with example how to use and what is the purpose of AssertTimeout assertion method.
AssertTimeout is used to verify whether a certain operation completes within the specified timeout or not.
For our example we will use the below class to be tested.
Class to be tested
package package12;
public class Calculator {
private int a, b;
public Calculator(int a, int b) {
this.a = a;
this.b = b;
}
public int add() throws InterruptedException {
Thread.sleep(500);
return this.a + this.b;
}
public int substract() throws InterruptedException {
Thread.sleep(1500);
return this.a - this.b;
}
}
In the above code, we have two methods “add” and “substract”. In these methods we have used Thread.sleep to simulate a time taking operation.
Below is the test class
Test Class
1 package package12;
2
3 import static org.junit.jupiter.api.Assertions.assertTimeout;
4
5 import java.time.Duration;
6
7 import org.junit.jupiter.api.Test;
8
9 public class CalculatorTest {
10 @Test
11 public void testAdd() {
12 Calculator calculator = new Calculator(5, 3);
13 assertTimeout(Duration.ofMillis(1000), () -> {calculator.add();});
14 }
15
16 @Test
17 public void testSubstract() {
18 Calculator calculator = new Calculator(5, 3);
19 assertTimeout(Duration.ofMillis(1000), () -> {calculator.substract();});
20 }
21 }
In the above code, at line 13, we are calling “assertTimeout” method passing the duration in which the test method has to complete and the actual test method is passed as lambda. In this case, the assert will pass as the test method
takes less than 1000 ms to complete.
At line 19, we are calling again “assertTimeout” method passing the duration within which the test method has to complete and the actual test method is passed as lambda. In this case, the assert will fail as the test method takes more
than 1000 ms to complete.
In this way we can use assertTimeout.