TestNG @AfterClass Annotation

By Arvind Rai, March 23, 2023
In TestNG test class, we can have a method that will run before test class destruction. To create such method, we need to use @AfterClass annotation. The @AfterClass annotated method will run after all the test methods in the current class have been run.
Find the code snippet to use @AfterClass annotation.
public class MyTestOne {
  ------ 
  @AfterClass
  public void destroy() {
    System.out.println("Resources are released.");
  }  
} 
The @AfterClass method can be used to release the resources used by test methods, close database connections etc.

Using @AfterClass

Example-1: In this example, we have a test class containing a method annotated with @AfterClass and a method annotated with @Test. In the output we will see that @AfterClass method is running after @Test method.
MyTestOne.java
package com.concretepage;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

public class MyTestOne {
  @Test
  public void divisionTest() {
	System.out.println("...divisionTest...");
	assertEquals(30 / 5, 6);
  }
  @AfterClass
  public void destroy() {
    System.out.println("MyTestOne: Resources are released.");
  }  
} 
Example-2: In this example, we have a @AfterClass method and two @Test methods. The @AfterClass method will run after last test method.
MyTestTwo.java
package com.concretepage;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;

public class MyTestTwo {
  @Test
  public void addTest() {
	System.out.println("...addTest...");
	assertEquals(70 + 30, 100);
  }
  @Test
  public void multiplyTest() {
	System.out.println("...multiplyTest...");	
	assertEquals(4 * 16, 64);
  }
  @AfterClass
  public void destroy() {
    System.out.println("MyTestTwo: Resources are released.");
  }  
} 

Running Test Classes

Method-1: In eclipse to run test classes, right click on test file -> Run As ->TestNG.
Method-2: Create testng.xml and configure all test classes that we have created.
src/test/resources/testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Suite1" verbose="1" >
  <test name="Regression1">
    <classes>
      <class name="com.concretepage.MyTestOne"/>
      <class name="com.concretepage.MyTestTwo"/>
    </classes>
  </test>
</suite> 
To run testng.xml, right click on xml file -> Run As ->TestNG.
Find the output in console.
TestNG @AfterClass Annotation

Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE







©2024 concretepage.com | Privacy Policy | Contact Us