1. TestNg annotation: @BeforeTest
2. TestNg annotation: @AfterTest
3. TestNg annotation: @BeforeSuite
4. TestNg annotation: @AfterSuite
5. TestNg annotation: @BeforeMethod
6. TestNg annotation: @AfterMethod
TestNg annotation: @BeforeTest
Let’s say, before you run any test case, there is a pre-requisite to clean the data that you have created in the database. This can be achieved using @BeforeTest.
Thus, @BeforeTest annotation would be given first priority (no matter in which class it is written).
See below the usage of @BeforeTest annotation
Let us run this as ‘TestNG Test’
Notice that @BeforeTest gets executed first
TestNg annotation: @AfterTest
Now let us change @BeforeTest to @AfterTest, see below. Let us keep the print message same
Run, notice that the sop message for @AfterTest gets printed after all the tests are executed
Thus, @AfterTest can be used to delete cookies, close browsers, generate reports, close db connections etc.
TestNg annotation: @BeforeSuite
@BeforeSuite can be used if you want to set some global environment variables to your framework. For example, for every release, we will have some new url (development, test or staging etc). You can set these urls as part of @BeforeSuite, so that all the tests get executed with that url.
Let us add this annotation to the last test of below class
Run as suite
See below. “Before suite…” sop is printed at the top
TestNg annotation: @AfterSuite
Let us add @AfterSuite annotation before the first test of another class viz TestNGDemo.java, see below
Run the testng.xml, see below
Notice ‘hello’ getting printed at the last, since @AfterSuite gets executed at the end
TestNg annotation: @BeforeMethod
You can use @BeforeMethod to clear cache, cookies etc before executing a method.
Now we know each @Test is a method. So if there are 4 @Test (methods) in a class, than @BeforeMethod will be executed 4 times before each @Test.
We see that there are 3 tests in the below class.
Let us add @BeforeMethod
Run as ‘TestNG Test’
Notice below that @BeforeMethod gets executed 3 times viz before each of the 3 tests
TestNg annotation: @AfterMethod
This is just reverse.
Let us change @BeforeMethod to @AfterMethod, change print statement (line 28)
Run test, see that @AfterMethod gets executed 3 times, but this time, after each @Test