Reputation: 145
I was playing around with TestNG and found that @AfterMethod & @BeforeMethod is getting invoked more than once when I'm using dataProvider. Is it possible to invoke a method only once after the @Test got executed with all the parameters passed from dataProvider. Like can we invoke 'tearDown' method only once after 'testPrimeNumberChecker' got called for 5 times by dataProvider.
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ParamTestWithDataProvider1 {
private PrimeNumberChecker primeNumberChecker;
private static final Logger logger = Logger.getLogger(ParamTestWithDataProvider1.class);
@BeforeMethod
public void initialize() {
logger.info("Before Method Fired !! - " );
primeNumberChecker = new PrimeNumberChecker();
}
@@AfterMethod
public void tearDown() {
logger.info("After Method Fired !! " );
}
@DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] { { 2, true }, { 6, false }, { 19, true },
{ 22, false }, { 23, true } };
}
@Test(dataProvider = "test1")
public void testPrimeNumberChecker(Integer inputNumber,
Boolean expectedResult) {
logger.info(inputNumber + " " + expectedResult);
Assert.assertEquals(expectedResult,
primeNumberChecker.validate(inputNumber));
}
}
Upvotes: 4
Views: 3370
Reputation: 677
One of the workarounds is to use ITestNGMethod#hasMoreInvocation
to check whether it is the last method invocation.
@AfterMethod(alwaysRun = true)
public void afterMethod(ITestResult testResult) {
if (!testResult.getMethod().hasMoreInvocation()) {
// This will be executed once, after a test method has been invoked for all parameters sequences defined in the corresponding @DataProvider
}
}
Please make sure to add alwaysRun = true
if you want the method to be executed even in case of failure.
Upvotes: 0
Reputation: 8531
One way can be to use @BeforeGroups and @AfterGroups. Make your test fall in a group and then use the Before/After groups annotation to do setup/teardown once for the tests.
Upvotes: 1
Reputation: 11
I want propose you a lazy idea:
You can use a TestListener extended class and put tearDown method into a specific method of this class (i.e. tearDownListener).
In onTestFailure and onTestSuccess you can increment a counter.
When TestListener intercept last test you can execute tearDownListener.
Regards
Upvotes: 1