Thursday 12 March 2020

TestNG: @AfterClass: Execute this method before executing all test cases

If you want to execute specific code after all the test cases are executed, then put that code inside a method and annotate that method with @AfterClass annotation.

Example
@AfterClass
public void afterClass_1() {
         System.out.println("Inside after class 1");
}

AfterClassTest.java
package com.sample.app.arithmetic;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AfterClassTest {
 @BeforeClass
 public void beforeClass_1() {
  System.out.println("Inside before class 1");
 }

 @BeforeClass
 public void beforeClass_2() {
  System.out.println("Inside before class 2");
 }

 @Test
 public void testCase1() {
  System.out.println("testCase1 executing");
 }

 @Test
 public void testCase2() {
  System.out.println("testCase2 executing");
 }

 @AfterClass
 public void afterClass_1() {
  System.out.println("Inside after class 1");
 }

}

Run AfterClassTest.java, you will see below messages in console.

Inside before class 1
Inside before class 2
testCase1 executing
testCase2 executing
Inside after class 1

Can I have more than one method annotated with @AfterClass annotation?
Yes

AfterClassTest.java

package com.sample.app.arithmetic;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class AfterClassTest {
 @BeforeClass
 public void beforeClass_1() {
  System.out.println("Inside before class 1");
 }

 @BeforeClass
 public void beforeClass_2() {
  System.out.println("Inside before class 2");
 }

 @Test
 public void testCase1() {
  System.out.println("testCase1 executing");
 }

 @Test
 public void testCase2() {
  System.out.println("testCase2 executing");
 }

 @AfterClass
 public void afterClass_1() {
  System.out.println("Inside after class 1");
 }

 @AfterClass
 public void afterClass_2() {
  System.out.println("Inside after class 2");
 }

}

Run AfterClassTest.java, you will see below messages in console.

Inside before class 1
Inside before class 2
testCase1 executing
testCase2 executing
Inside after class 1
Inside after class 2

Where can I use @AfterClass methods?
Following are some of the examples.
a.   Closing resources that are opened by test cases or @BeforeClass methods
b.   To perform any garbage collection activities etc.,





Previous                                                    Next                                                    Home

No comments:

Post a Comment