Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestNG Annotations order

Tags:

java

testng

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:

enter image description here

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!

like image 417
zmorris Avatar asked Sep 29 '22 17:09

zmorris


1 Answers

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.

like image 64
Neeraj Jain Avatar answered Oct 05 '22 07:10

Neeraj Jain