Reputation: 1077
I have a question about the order of operations with TestNG annotations... I have the following code:
public class AnnotationsTest {
@BeforeSuite(alwaysRun = true)
public static void beforeSuite() {
System.out.println("@BeforeSuite");
}
@BeforeClass(alwaysRun = true)
public static void beforeClass() {
System.out.println("@BeforeClass");
}
@BeforeTest(alwaysRun = true)
public static void beforeTest() {
System.out.println("@BeforeTest");
}
@BeforeMethod(alwaysRun = true)
public static void beforeMethod() {
System.out.println("@BeforeMethod");
}
@AfterSuite(alwaysRun = true)
public static void afterSuite() {
System.out.println("@AfterSuite");
}
@AfterClass(alwaysRun = true)
public static void afterClass() {
System.out.println("@AfterClass");
}
@AfterTest(alwaysRun = true)
public static void afterTest() {
System.out.println("@AfterTest");
}
@AfterMethod(alwaysRun = true)
public static void afterMethod() {
System.out.println("@AfterMethod");
}
@Test
public void test() {
System.out.println("Test");
}
@Test
public void test2() {
System.out.println("Test2");
}
}
My output is the following:
My question is, why is @AfterTest method not run after each @Test annotation? Does TestNG treat the entire class as the 'Test'? It seems like this is the case because the @BeforeTest and @AfterTest are outside of the @BeforeClass and @AfterClass, but I wanted to be sure I understand. I assume I could use the @BeforeMethod and @AfterMethod in this case to execute before and after the test1 and test2 in this class. Thanks!
Upvotes: 5
Views: 19207
Reputation: 29
@AfterMethod
is the one that executes after @Test
method. Similarly @BeforeMethod
is the one that executes before each @Test
method.
Your output shows the priority of methods running.
Upvotes: 0
Reputation: 1
The main confusion here is with @Test annotation and tag. Consider that you are executing above code from testng.xml file. And the way we write testng file tag sequence in that file is methods . So it now each annotation will make sense. i.e. @Test is used for methods within that class. @BeforeMethod will get execute before each @Test annotation. And @BeforeTest annotation execute before classes mentioned in testng.xml file as you can see tag encloses tag. So short anwser for above question is @Test is used for menthod @BeforeMethod is executed before each @Test annoted method and @BeforeTest is executed before all methods and classes mentioned in tag.
Upvotes: 0
Reputation: 7720
My question is, why is @AfterTest method not run after each @Test annotation?
As the Documentation says
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
and
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
Upvotes: 4