Thursday 12 March 2020

TestNG: @BeforeClass: Execute this method before executing test cases

If you want to execute specific snippet of code exactly once before executing test cases, then put that code in a method that is annotated with @BeforeClass annotation.

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

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

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

public class BeforeClassTest {

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

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

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

}

When you run BeforeClassTest application, you will see below messages in console.
Inside before class 1
testCase1 executing
testCase2 executing

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

package com.sample.app.arithmetic;

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

public class BeforeClassTest {

 @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");
 }

}

When you ran ‘BeforeClassTest’, you will get below messages in console.

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

Where can I use @BeforeClass methods?
Following are some of the examples.
a.   Driver initialization in selenium testing
b.   Data base connections initialization
c.    Profiles setting etc.,



Previous                                                    Next                                                    Home

No comments:

Post a Comment