Question

I have the following code:

@BeforeTest(alwaysRun = true)
public void setup() {
    System.out.println("@BeforeTest");
}

@DataProvider
public String[][] provideData() {
    System.out.println("@DataProvider");
    return new String[][] {
         {"string"},
         {"string2"},
         {"string3"}
    };
}

@Test(dataProvider = "provideData")
public void test(String s) {
    System.out.println("@Test");
    System.out.println(s);
}

@AfterTest(alwaysRun = true)
public void tearDown() {
    System.out.println("@AfterTest");
}

which produces the following output to the console:

@BeforeTest
@DataProvider
@Test
string
@Test
string2
@Test
string3
@AfterTest

I was expecting the @BeforeTest and @AfterTest methods to run before and after the test. I am writing WebDriver tests and would like to setup and teardown after each iteration of the data. What am I missing?

Was it helpful?

Solution 2

It looks like you're using TestNG, but you're used to JUnit. Here's a table that explains the annotations a bit more.

http://www.mkyong.com/unittest/junit-4-vs-testng-comparison/

OTHER TIPS

I think I have figured this out. I have a theory that the @BeforeTest and @AfterTest are only going to execute after ALL of the runs of the parameterized test are done, because there is only one @Test annotation. Changing this to @BeforeMethod and @AfterMethod seems to give the output I want:

@DataProvider
@BeforeTest
@Test
string
@AfterTest
@BeforeTest
@Test
string2
@AfterTest
@BeforeTest
@Test
string3
@AfterTest

I believe this is because the data provider sees this as a single test, but the method is executed multiple times, so it follows the before and after sequence appropriately.

You can use BeforeMethod and AfterMethod for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top