How to use TestNG @After Annotation?



A TestNG class can have various @After TestNG methods. Such as: @AfterTest @AfterSuite @AfterClass @AfterMethod etc.

This article will explain the order of execution of different TestNG methods.

TestNG consists of following @After methods to support main @Test method. The order of execution of @After methods should be as following:

<test1> <AfterMethod> <AfterClass> <AfterTest> <AfterSuite> 

Key Points in this Order are

  • First of all, 1st @test() method is executed in above example.

  • The AfterSuite() method executes only once.

  • Even the methods AfterClass(), and AfterTest() methods are executed only once.

  • AfterMethod() method executes for each test case (every time for a new @Test) but after executing the test case.

Approach/Algorithm to Solve this Problem

  • Step 1: import org.testng.annotations.* for TestNG.

  • Step 2: Write an annotation as @test

  • Step 3: Create a method for the @test annotation as test1.

  • Step 4: Repeat the steps for test2 and test3.

  • Step 5: Write different annotations and their respective methods. Ex:, @AfterClass, @AfterMethod, @AfterSuite

  • Step 5: Now create the testNG.xml as given below.

  • Step 6: Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line.

Example

The following code to show the order of different TestNG methods:

import org.testng.annotations.*; import org.testng.annotations.Test; public class OrderofTestExecutionInTestNG { // test case 1 @Test public void testCase1() { System.out.println("in test case 1"); } // test case 2 @Test public void testCase2() { System.out.println("in test case 2"); } @AfterMethod public void afterMethod() { System.out.println("in afterMethod"); } @AfterClass public void afterClass() { System.out.println("in afterClass"); } @AfterTest public void afterTest() { System.out.println("in afterTest"); } @AfterSuite public void afterSuite() { System.out.println("in afterSuite"); } } 

testng.xml

This is a configuration file that is used to organize and run the TestNG test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "OrderofTestExecutionInTestNG"/> </classes> </test> </suite> 

Output

in test case 1 in afterMethod in test case 2 in afterMethod in afterClass in afterTest in afterSuite 
Updated on: 2023-08-21T11:37:06+05:30

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements