Over a million developers have joined DZone.

TestNG @Test Annotation – using timeOut Attribute

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

While running test methods there can be cases where certain test methods get struck or may take long time than to complete than expected. In such cases we may need to mark the said test case as fail and then continue with the next test case.

TestNG allows user to configure a time period to wait for a test to completely execute before it can be marked as FAILED.

Here is a quick example

Code

Service Class

package com.skilledmonster.example;
import org.testng.annotations.Test;
/**
* Example to demonstrate use of timeOut attribute of @Test Annotation
*
* @author Jagadeesh Motamarri
* @version 1.0
*/
public class TestNGAnnotationTestMethodTimeOutExample {
@Test(timeOut = 2000)
public void timeOutTestMethodOne() throws InterruptedException {
Thread.sleep(5000);
System.out.println("TimeOut Test Method One!!");
}
@Test(timeOut = 5000)
public void timeOutTestMethodTwo() throws InterruptedException {
Thread.sleep(3000);
System.out.println("TimeOut Test Method Two!!");
}
@Test(timeOut = 2000)
public void timeOutTestMethodRunForEver() {
while (true) {
// Do nothing
}
}
}

In this example there are 3 test methods -

timeOutTestMethodOne() – time out for this method is set to 2 seconds but the current thread that is executing this method goes to sleep for 5 seconds during the executing of the method and eventually the test fails because thread sleep time is more than time out set on the test method.

timeOutTestMethodTwo() – time out for this method is set to 5 seconds but the current thread sleeps only 3 seconds giving a chance for the test method to complete (probably) before the time out.

timeOutTestMethodRunForEver() – this test methods fails after waiting for 2 seconds due to the infinity loop.

Output

 testng_timeout 

Download

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Jagadeesh Motamarri, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}