All Posts

JUnit Timeout Test

JUnit Timeout Test

In this tutorial, you will learn JUnit Timeout Test. The “Timeout Test” tests if a test method is taking longer time than the specified number of time (in milliseconds) to execute, then the test method will be terminated and marked as failed.

While running test methods there can be cases where certain test methods get struck or may take longer time than to complete the execution than the expected. We need to handle these type of cases by specifying Timeout and proceed to execute further test cases / methods.

Sample Code

import org.junit.Ignore;
import org.junit.Test;
public class JUnitExamples {
	@Test
	public void testCaseSample(){
			System.out.println("Sample Test Method.");
		}

       // You can specify time in milliseconds
	@Test(timeout=3000) 
	public void timeOutExample(){
		while(true);
	}
}

 

Sample Output

When we execute the above program, it will display the output as “2 tests executed.
Test Method : testCaseSample – PASSED

Test Method : timeOutExample – FAILED
Error – java.lang.Exception: test timed out after 3000 milliseconds

The second method will be marked as Fail, because the execution is not completed in the specified timeOut period. It will stop the execution forcibly and return as FAILED