deepak.mr888
deepak.mr888

Reputation: 349

How to set invocationCount value at run time in TestNG @Test Annotation

I got stuck at one point in my framework.

I want to run a @Test annotation for multiple number of times. For this I have googled it and found a solution to set invocationCount variable with @Test annotation.

So what I did is :

@Test(invocationCount=3)

This was working perfectly for me. But my problem is that I want to set the value of this parameter with a variable.

E.g. I have a variable & what I want is like :

int x=5;

@Test(invocationCount=x)

Is there any possible way to do this or any other good approach to execute the same @Test annotation for number of times.

Thanks in advance.

Upvotes: 2

Views: 9291

Answers (1)

juherr
juherr

Reputation: 5740

Set TestNG timeout from testcase is a similar question.

You have 2 options:

If x is constant, you can use a IAnnotationTransformer.

Otherwise, you can use hack like:

public class DynamicTimeOutSample {

  private final int count;

  @DataProvider
  public static Object[][] dp() {
    return new Object[][]{
        new Object[]{ 10 },
        new Object[]{ 20 },
    };
  }

  @Factory(dataProvider = "dp")
  public DynamicTimeOutSample(int count) {
    this.count = count;
  }

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

  @Test
  public void test() {
  }
}

Upvotes: 1

Related Questions