Fredrik Johansson
Fredrik Johansson

Reputation: 1301

Set TestNG timeout from testcase

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.

Upvotes: 3

Views: 1254

Answers (1)

juherr
juherr

Reputation: 5740

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

Upvotes: 3

Related Questions