0
0
Selenium Javatesting~5 mins

TestNG annotations (@Test, @BeforeMethod, @AfterMethod) in Selenium Java

Choose your learning style9 modes available
Introduction

TestNG annotations help organize and control test execution steps easily. They tell the test framework what to run and when.

You want to run setup code before each test, like opening a browser.
You want to run cleanup code after each test, like closing the browser.
You want to mark a method as a test case to be executed automatically.
You want to keep test code clean by separating setup, test, and teardown steps.
Syntax
Selenium Java
@BeforeMethod
public void setup() {
    // code to run before each test
}

@Test
public void testExample() {
    // test code
}

@AfterMethod
public void teardown() {
    // code to run after each test
}

@BeforeMethod runs before each test method.

@AfterMethod runs after each test method.

Examples
This example shows simple print statements to simulate opening and closing a browser around a test.
Selenium Java
@BeforeMethod
public void openBrowser() {
    System.out.println("Browser opened");
}

@Test
public void testLogin() {
    System.out.println("Login test running");
}

@AfterMethod
public void closeBrowser() {
    System.out.println("Browser closed");
}
A simple test method marked with @Test to run as a test case.
Selenium Java
@Test
public void testSearch() {
    System.out.println("Search test running");
}
Sample Program

This test class uses @BeforeMethod to open the browser before each test, @Test to run the test, and @AfterMethod to close the browser after each test.

Selenium Java
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

public class SampleTest {

    @BeforeMethod
    public void setup() {
        System.out.println("Setup: Open browser");
    }

    @Test
    public void testGoogleTitle() {
        System.out.println("Test: Check Google title");
        // Imagine test code here
    }

    @AfterMethod
    public void teardown() {
        System.out.println("Teardown: Close browser");
    }
}
OutputSuccess
Important Notes

Each test method runs with fresh setup and teardown, keeping tests independent.

Use @BeforeMethod and @AfterMethod for actions needed before and after every test.

TestNG runs methods with these annotations automatically; no need to call them yourself.

Summary

@Test marks a method as a test case.

@BeforeMethod runs before each test method to prepare the environment.

@AfterMethod runs after each test method to clean up.