TestNG @BeforeClass Annotation

By Arvind Rai, March 22, 2023
In TestNG test class, we can have a method that will run just after class initialization. To create such method, we need to use @BeforeClass annotation. The @BeforeClass annotated method will run before the first test method in the current class.
Find the code snippet to use @BeforeClass annotation.
public class MySimpleTest {
  @BeforeClass
  public void setUp() {
	System.out.println("Test setup completed.");
  }
  ------
} 
The @BeforeClass can be used to setup some configurations used by all tests such as database connection, creating seed data etc.

Using @BeforeClass

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

public class MySimpleTestOne {
  @BeforeClass
  public void setUp() {
	System.out.println("MySimpleTestOne: Test setup completed.");
  }
  @Test
  public void divisionTest() {
	System.out.println("...divisionTest...");
	assertEquals(20 / 5, 4);
  }
} 
Example-2: In this example, we have a @BeforeClass method and two @Test methods. The @BeforeClass method will run before first test method.
MySimpleTestTwo.java
package com.concretepage;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class MySimpleTestTwo {
  @BeforeClass
  public void setUp() {
	System.out.println("MySimpleTestTwo: Test setup completed.");
  }
  @Test
  public void addTest() {
	System.out.println("...addTest...");
	assertEquals(20 + 30, 50);
  }
  @Test
  public void multiplyTest() {
	System.out.println("...multiplyTest...");	
	assertEquals(5 * 15, 75);
  }
} 

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.MySimpleTestOne"/>
      <class name="com.concretepage.MySimpleTestTwo"/>
    </classes>
  </test>
</suite> 
To run testng.xml, right click on xml file -> Run As ->TestNG.
Find the output in console.
TestNG @BeforeClass Annotation

Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE







©2024 concretepage.com | Privacy Policy | Contact Us