TestNG Test Annotations Order
Don't know about you, but i keep forgetting the right order of Test run Annotations order. Especially if i work on JUnit and TestNG projects at the same time ( yeah, it's quite common). So, this article is basically for me in the first place - so i could look up into it when i forget the right order. I saw this simple solution in one of the StackOverflow answers and wanted to save it for me. Maybe it will help you as well.
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");
}
}
And the output is the answer to our question :
[TestNG] Running:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
Test
@AfterMethod
@BeforeMethod
Test2
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================