#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
TestNG & Maven

TestNG Annotations

Common Annotations

  • @Test — marks a method as a test case.
  • @BeforeMethod / @AfterMethod — run before/after each test method.
  • @BeforeClass / @AfterClass — run once before/after all tests in a class.
  • @BeforeSuite / @AfterSuite — run once before/after the entire suite.
  • @DataProvider — supplies multiple sets of data to a test method for data-driven testing.

Why Annotations Matter

Annotations let testers precisely control the setup and teardown lifecycle around each test, avoiding repeated boilerplate code.

The Order in Which Annotations Run

When TestNG runs a suite, the configuration methods wrap the tests like layers of an onion. For a suite with one test tag and one class containing two tests, the order is:

  1. @BeforeSuite
  2. @BeforeTest (for each <test> tag in testng.xml)
  3. @BeforeClass
  4. @BeforeMethod, then the first @Test, then @AfterMethod
  5. @BeforeMethod, then the second @Test, then @AfterMethod
  6. @AfterClass
  7. @AfterTest
  8. @AfterSuite

There are also @BeforeGroups and @AfterGroups, which run around tests that belong to a named group.

Worked Example: A Selenium Test Class

public class LoginTests {
    WebDriver driver;

    @BeforeClass
    public void setUp() {
        driver = new ChromeDriver();
    }

    @BeforeMethod
    public void openLoginPage() {
        driver.get("https://example.com/login");
    }

    @Test(priority = 1, groups = "smoke")
    public void validLogin() {
        // enter valid credentials and assert the dashboard loads
    }

    @Test(priority = 2, dataProvider = "badUsers")
    public void invalidLogin(String user, String pass) {
        // enter bad credentials and assert an error message
    }

    @DataProvider(name = "badUsers")
    public Object[][] badUsers() {
        return new Object[][] {
            {"wrong@example.com", "Secret123"},
            {"tester@example.com", "wrongpass"},
            {"", ""}
        };
    }

    @AfterMethod
    public void captureOnFailure(ITestResult result) {
        if (result.getStatus() == ITestResult.FAILURE) {
            // take a screenshot here
        }
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }
}

The browser opens once per class, the login page reloads before each test, and the data provider makes invalidLogin run three times with different inputs.

The ITestResult parameter in @AfterMethod is injected by TestNG automatically, so the cleanup method can see whether the test that just ran passed, failed or was skipped. Configuration methods can also receive other objects, such as ITestContext for suite-level details or Method to know which test is about to run. To run only the smoke group, list it under the include tag of the groups section in testng.xml.

Useful Attributes of @Test

AttributeWhat It Does
priorityLower numbers run first when no dependency decides the order
groupsTags tests, for example "smoke" or "regression", so testng.xml can include or exclude them
dependsOnMethodsSkips the test if a named test failed
enabledSet to false to switch a test off temporarily
timeOutFails the test if it runs longer than the given milliseconds
expectedExceptionsPasses only if the listed exception is thrown
invocationCountRuns the same test several times

Common Annotation Mistakes

  • Heavy work in @BeforeMethod. Starting a browser before every single test makes suites slow; use @BeforeClass when tests can share it safely.
  • Relying on priority for data flow. If test B needs data from test A, prefer dependsOnMethods or, better, make each test create its own data.
  • Shared driver in parallel runs. A single field shared across threads causes random failures. Use a ThreadLocal driver when running tests in parallel.
  • Mixing JUnit and TestNG imports. An @Test from the wrong package is silently ignored by the TestNG runner.
  • Forgetting alwaysRun = true on cleanup methods that must run even when group filters are applied.

Ready to master real-world software testing?

Learn manual and automation testing hands-on with mentor-led sessions.

Explore Course