Timeout Test in TestNG

When a test method is taking longer time than the specified time (in milliseconds) to execute, then that test method will be terminated and marked as failed, this feature is available in both JUnit 4 and TestNG.

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

TestNG Example:

import org.testng.annotations.Test;
public class TestNGExamples {
	@Test
	public void sampleTestCase(){
			System.out.println("Im ready to execute");
		}
	@Test(timeOut=1000) // specify time in milliseconds
	public void executetimeOut() throws InterruptedException{
		Thread.sleep(3000);
             // Thread.sleep(500);
	}
}

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

Test Method : executetimeOut – FAILED
Error – org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.executePass() didn't finish within the time-out 1000

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

The Method will return as “PASSED”, if we change the value of milliseconds to lessthan 1000 which specified in timeout. As “Thread.sleep(500);”. The test will complete the executing within the timeout period, hence this will return as “Passed”

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.