Thursday, 12 March 2020

TestNG: @BeforeMethod: Execute before every test case

If you annotate a method with @BeforeMethod annotation, then that method gets executed before every test case gets executed.

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

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

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

public class BeforeMethodTest {
 @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");
 }

 @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("\nInside after class 1");
 }

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

}

Run BeforeMethodTest.java, you can see below messages in console.
Inside before class 1
Inside before class 2

Inside beforeMethod_1
testCase1 executing

Inside beforeMethod_1
testCase2 executing

Inside after class 1
Inside after class 2

Can I define more than one method with @BeforeMethod annotation?
Yes

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

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

public class BeforeMethodTest {
 @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");
 }

 @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 BeforeMethodTest class, you will see below messages in console.

Inside before class 1
Inside before class 2

Inside beforeMethod_1
Inside beforeMethod_2
testCase1 executing

Inside beforeMethod_1
Inside beforeMethod_2
testCase2 executing

Inside after class 1
Inside after class 2


Previous                                                    Next                                                    Home

No comments:

Post a Comment