Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set TestNG timeout from testcase

Tags:

java

testng

I've seen lots of examples similar to this:

@Test(timeOut = 1000)

Is it possible to override the timeout value from within the testcase? If so, how?

My problem is that the execution time of the testcase is controlled by an argument that is passed to the testcase. Sometimes the testcase takes one hour, sometimes many days. I want to set the timeout accordingly.

like image 712
Fredrik Johansson Avatar asked Aug 16 '26 09:08

Fredrik Johansson


1 Answers

It is possible but it is very a tricky hack that I don't recommend.

public class DynamicTimeOutSample {

  private final long timeout;
  private final long waitTime;

  @DataProvider
  public static Object[][] dp() {
    return new Object[][]{
        new Object[]{ 1_000, 2_000 },
        new Object[]{ 3_000, 6_000 },
    };
  }

  @Factory(dataProvider = "dp")
  public DynamicTimeOutSample(long timeout, long waitTime) {
    this.timeout = timeout;
    this.waitTime = waitTime;
  }

  @BeforeMethod
  public void setUp(ITestContext context) {
    ITestNGMethod currentTestNGMethod = null;
    for (ITestNGMethod testNGMethod : context.getAllTestMethods()) {
      if (testNGMethod.getInstance() == this) {
        currentTestNGMethod = testNGMethod;
        break;
      }
    }
    currentTestNGMethod.setTimeOut(timeout);
  }

  @Test
  public void test() throws InterruptedException {
    Thread.sleep(waitTime);
  }
}

The twice test cases of the example will fail as expected.

I created the feature request, but don't expect to have it soon: https://github.com/cbeust/testng/issues/1061

like image 120
juherr Avatar answered Aug 18 '26 23:08

juherr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!