Thursday 12 March 2020

TestNG: AfterMethod: Execute after every test case executed

If you annotate any method with @AfterMethod annotation, then this method will get executed after every test case executed successfully.

@AfterMethod
public void afterMethod_2() {
         System.out.println("Inside afterMethod_2");
}

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

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

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

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

 @BeforeMethod
 public void beforeMethod_1() {
  System.out.println("\nInside beforeMethod_1");
 }

 @BeforeMethod
 public void beforeMethod_2() {
  System.out.println("Inside beforeMethod_2");
 }

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

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

 @AfterMethod
 public void afterMethod_1() {
  System.out.println("Inside afterMethod_1");
 }

 @AfterMethod
 public void afterMethod_2() {
  System.out.println("Inside afterMethod_2");
 }

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

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

}

When you ran AfterMethodTest.java, you will see below messages in console.

Inside before class 1
Inside before class 2

Inside beforeMethod_1
Inside beforeMethod_2
testCase1 executing
Inside afterMethod_1
Inside afterMethod_2

Inside beforeMethod_1
Inside beforeMethod_2
testCase2 executing
Inside afterMethod_1
Inside afterMethod_2

Inside after class 1
Inside after class 2





Previous                                                    Next                                                    Home

No comments:

Post a Comment