Timeout Test in JUnit

Timeout Test
The “Timeout Test” means 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

Example:

 
import org.junit.Ignore;
import org.junit.Test;
public class JUnitExamples {
	@Test
	public void testCaseBanking(){
			System.out.println("Im ready to execute");
		}

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

When we execute the above program, it will display the output as “2 tests executed.
Test Method : testCaseBanking – 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. Hence it will stop the execution forcibly and returns as FAILED

Test Frameworks: 

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.