</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

How can we run a test method multiple times in a loop without using any data provider?

Use the invocationCount parameter in @Test annotation to run a test method N times in a loop without needing @DataProvider.

Answer

Running a Test Method Multiple Times in a Loop

Set invocationCount in the @Test annotation to make a test run N times in a loop without any data provider.

Example — run getTitle() 5 times:

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class InvocationCountLoop {

    @Test(invocationCount = 5)
    public void getTitle() {
        System.setProperty("webdriver.chrome.driver", "C://Drivers/chromedriver_win32/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.pavantestingtools.com/");
        driver.manage().window().maximize();
        System.out.println("Website Title: " + driver.getTitle());
        driver.quit();
    }

    @Test
    public void secondTest() {
        System.out.println("This will be executed at the end");
    }
}

Execution order:

  1. getTitle() runs — iteration 1
  2. getTitle() runs — iteration 2
  3. getTitle() runs — iteration 3
  4. getTitle() runs — iteration 4
  5. getTitle() runs — iteration 5
  6. secondTest() runs — once

Getting current invocation index:

Java
@Test(invocationCount = 5)
public void repeatedTest(ITestContext context) {
    // ITestResult gives you the invocation count
    System.out.println("Invocation #" + (System.currentTimeMillis()));
}

With parallel threads:

Java
@Test(invocationCount = 10, threadPoolSize = 5)
public void parallelRepeatedTest() {
    // Runs 10 times using up to 5 parallel threads
    System.out.println("Thread: " + Thread.currentThread().getName());
}

Difference from @DataProvider:

  • invocationCount = 5 → runs same logic 5 times, same data each time
  • @DataProvider → runs same logic N times, different data each time

When to use invocationCount:

  • Confirming a flaky test is not intermittently failing
  • Performance/stress testing a specific action
  • Running a teardown/setup cycle N times

Follow AutomateQA

Related Topics