Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 29 ยท TestNG core

TestNG Annotations and Lifecycle

Learn TestNG's nine setup and teardown annotations, the order they run in, what happens when setup fails, and the enabled and description attributes of @Test.

TestNG has a richer lifecycle than JUnit. Where JUnit has four setup and cleanup annotations (@BeforeAll, @BeforeEach and their After twins), TestNG has four levels of scope, each with a Before and an After annotation: the whole suite, a <test> group of classes, a single class, and a single method. That gives you precise control, for example "start the web server once for the whole run, but open a fresh browser for every class, and clear cookies after every method".

The price is that you must know the order and the meaning of each level. This lesson explains both. You will see the real TestNG code as read-only snippets, because a TestNG run needs a build tool and the TestNG jar, which our in-browser runners do not have. To make the order tangible, you will also run a small stand-in in JavaScript that replays exactly the same lifecycle rules with plain functions. The stand-in is not TestNG, but its order and failure rules follow TestNG's documented behavior.

If you have not seen a TestNG class yet, start with Your First TestNG Test.

Four levels of scope

Suite The whole run, once.
Test One group of classes in testng.xml.
Class Once per test class.
Method Around every @Test method.

Each level has a Before and an After annotation.

1 / 3

The nine lifecycle annotations

All of these come from org.testng.annotations. They mark configuration methods, which TestNG calls around your tests but does not count as tests.

Annotation Runs Typical use
@BeforeSuite / @AfterSuite once before / after everything in the suite start and stop a shared server, load settings
@BeforeTest / @AfterTest before / after the classes of a <test> tag in testng.xml per-group setup, such as one database for the "api" group of classes
@BeforeClass / @AfterClass once before the first / after the last test method of the class expensive per-class objects
@BeforeMethod / @AfterMethod before / after every @Test method fresh state per test
@BeforeGroups / @AfterGroups before the first / after the last method of the named groups setup for a group, see TestNG Assertions and Groups

A word of warning about the name: @BeforeTest has nothing to do with a single test method. "Test" here means the <test> element of testng.xml (explained in testng.xml, Suites and Test Configuration). Developers coming from JUnit often assume @BeforeTest equals @BeforeEach, and it does not: the per-method annotation is @BeforeMethod. If you run a class without an XML file, TestNG creates a default suite and a default test around it, so @BeforeTest runs once for the whole run.

flowchart TD
  A["@BeforeSuite"] --> B["@BeforeTest"]
  B --> C["@BeforeClass"]
  C --> D["@BeforeMethod"]
  D --> E["@Test method"]
  E --> F["@AfterMethod"]
  F -->|"next method"| D
  F --> G["@AfterClass"]
  G --> H["@AfterTest"]
  H --> I["@AfterSuite"]

The nesting: the method pair repeats for every test method, the class pair for every class, and so on outward.

A real TestNG class (read-only)

Here is a test class that logs each lifecycle step, written with the real TestNG API. It cannot run on this page.

Java
import org.testng.annotations.*;

public class OrderServiceTest {

    @BeforeSuite
    public void startServer() { System.out.println("@BeforeSuite startServer"); }

    @BeforeClass
    public void createService() { System.out.println("@BeforeClass createService"); }

    @BeforeMethod
    public void openTransaction() { System.out.println("@BeforeMethod openTransaction"); }

    @Test(description = "A new order starts with status NEW")
    public void newOrderIsNew() { /* ... */ }

    @Test(enabled = false, description = "Waiting for the payment sandbox")
    public void paymentIsCaptured() { /* ... */ }

    @AfterMethod(alwaysRun = true)
    public void rollback() { System.out.println("@AfterMethod rollback"); }

    @AfterClass(alwaysRun = true)
    public void closeService() { System.out.println("@AfterClass closeService"); }

    @AfterSuite(alwaysRun = true)
    public void stopServer() { System.out.println("@AfterSuite stopServer"); }
}

Three details in this class matter. description is free text that appears in reports. enabled = false makes TestNG skip the method completely: it is not run, and its before and after method hooks are not run for it either. And the cleanup methods use alwaysRun = true, which we come back to below.

Replaying the order

The stand-in below describes a suite as plain data: hooks at every level, two <test> groups, and test methods as functions. The function runSuite walks it in TestNG's order and prints each step with indentation showing the nesting. Edit the code, add hooks or a method, and watch where the new line lands.

JS Stand-in: the TestNG lifecycle order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look for the rules in the output:

  • Suite and test hooks appear once; the OrderServiceTest pair @BeforeClass/@AfterClass wraps its methods, and @BeforeMethod/@AfterMethod wraps each one.
  • Methods run in name order, not source order (cancelledOrderCannotShip before newOrderIsNew). Never rely on it; control order explicitly as shown in Dependencies, Priority and Test Ordering.
  • The disabled method gets no @BeforeMethod and no @AfterMethod.
  • A failing test does not stop its neighbours or the after hooks.

When setup fails

A failing configuration method is different from a failing test. If a @BeforeClass method throws, TestNG cannot run the tests that depended on that setup, so it marks them skipped rather than failed, and by default it also skips the later cleanup methods. Cleanup that must always happen (closing a connection, stopping a server) should be declared with alwaysRun = true. Likewise, @BeforeMethod and @BeforeClass methods marked alwaysRun run even when their groups were not selected. The second example uses the same runSuite idea, trimmed, to show a failing @BeforeClass.

JS Stand-in: a failing @BeforeClass

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The two tests are reported as skipped, not failed: the report tells you "the environment was broken", which is a different problem from "the code is wrong". deleteTempFiles ran because of alwaysRun; closeConnection did not. In real TestNG you read these as the skipped counter in the report next to passed and failed, and the exception of the failed configuration method is shown once at the top.

Inheritance order

Lifecycle methods are inherited. With a base class BaseTest and a subclass CheckoutTest, TestNG runs the superclass @Before... methods first, then the subclass ones, and for @After... methods it reverses the order: subclass first, superclass last. Shared base classes are a common place to keep setup such as a driver or a client; keep them small, because every test class inherits them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation runs before every single @Test method in a TestNG class?

    @BeforeMethod is the per-method hook, the equivalent of JUnit's @BeforeEach. @BeforeTest refers to the <test> element of testng.xml, not to a test method.
  2. 2. A suite has one class with three test methods and uses @BeforeClass and @BeforeMethod. How many times does each run?

    The class level runs once for the class. The method level runs around each of the three methods.
  3. 3. What happens to the test methods when a @BeforeClass method throws an exception?

    Tests cannot run without their configuration, so TestNG skips them. Cleanup methods marked alwaysRun = true still run.
  4. 4. What does @Test(enabled = false) do?

    A disabled test is not run at all. It is still better to fix or delete it soon, because disabled tests are easy to forget.

Summary

  • TestNG has four scopes with a Before and an After annotation each: suite, <test>, class and method (plus groups).
  • Order: BeforeSuite, BeforeTest, BeforeClass, then BeforeMethod / Test / AfterMethod for each method, then AfterClass, AfterTest, AfterSuite.
  • @BeforeTest means "before the <test> element in testng.xml", not "before each test method".
  • A failed configuration method makes dependent tests skipped; mark cleanup methods alwaysRun = true so they still run.
  • @Test(enabled = false) skips a method; description documents it in reports. Do not rely on method order unless you set it.

Next: TestNG Assertions and Groups.