We have a scenario where if our test case is taking more time to execute than that of the expected time then we can restrict using Junit to wait for specified amount of milliseconds and proceed further to rest of the test cases.
Let’s see how we are going to achieve this with an example :
Example 1 :
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.junit.Test; public class TimeOutJunit1 { @Test(timeout=5000) public void timeoutJunitExample() throws InterruptedException { System.out.println("Started the execution"); Thread.sleep(5000); System.out.println("ended the execution"); } } |
OUTPUT :
Junit-Timeout-Example1 Junit-Timeout-Example4
Junit will throw an “TestTimedOutException” error if the above test is not executed within 5 milliseconds and marks this test case as failed.
Let’s see how we are going to achieve this with an example :
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.junit.Test; public class TimeOutJunit1 { @Test(timeout=5000) public void timeoutJunitExample() throws InterruptedException { System.out.println("Started the execution"); Thread.sleep(2000); System.out.println("ended the execution"); } } |
OUTPUT :
Junit-Timeout-Example2
Junit-Timeout-Example3
Junit will execute both the statements as there is no TimedoutException occurs. Because two statements are executed within 3 seconds.