TestNG BeforeClass and AfterClass

Profile picture for user arilio666

This article will see about before and after class annotations used in TestNG.


The @BeforeClass annotation is used to run tests before the execution of test methods in the current class.


The @AfterClass annotation runs tests after the execution of test methods has been invoked in the current class.

package week4.day2;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PopUp {
    private void test1() {
        System.out.println("I came BeforeClass");
    private void test2() {
        System.out.println("I come AfterClass");
    public void popUp() throws Throwable {
        ChromeDriver driver = new ChromeDriver();
        List<WebElement> elementTexts = driver.findElements(By.xpath("//div[@class='header__main__left']"));
        for (WebElement webElement : elementTexts) {
  • We can witness here that the two methods, test1 and test2 with @BeforeClass and @AfterClass annotations, have run and been executed according to their behavior.