skip to content

In TestNG, when a test class extends a base class and both declare @BeforeClass and @BeforeMethod hooks, in what order do they run?

level: middleimportance: should knowfreq 48%

answer

  1. scope beats inheritance
  2. top of the hierarchy first
  3. teardown climbs back up
  4. same scope, same class: unordered

basics

~10 s

Scope nests first, inheritance second: every class-level hook runs before any method-level one, and within one scope the superclass's @Before hook runs before the subclass's, while @After hooks run subclass first, then superclass.

solid answer

~40 s

TestNG documents that `@Before` methods run in inheritance order, highest superclass first and down the chain, and `@After` methods in reverse, back up the chain. That ordering applies within a scope; the scope ladder still dominates. So for one test method the sequence is base `@BeforeClass`, subclass `@BeforeClass`, base `@BeforeMethod`, subclass `@BeforeMethod`, the test, subclass `@AfterMethod`, base `@AfterMethod`, then subclass and base `@AfterClass`. A base hook runs for every subclass that inherits it. Two hooks of the same scope declared in one class have no documented order; if one needs the other, declare `dependsOnMethods` on the hook. Give base and subclass hooks distinct names, because a same-signature method in the subclass overrides the base one in Java.

code

java · 26 lines
java
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

abstract class BaseTest {
  @BeforeSuite  public void baseSuite()       { System.out.println("1 base   @BeforeSuite"); }
  @BeforeClass  public void baseClass()       { System.out.println("3 base   @BeforeClass"); }
  @BeforeMethod public void baseMethod()      { System.out.println("5 base   @BeforeMethod"); }
  @AfterMethod  public void baseAfterMethod() { System.out.println("9 base   @AfterMethod"); }
  @AfterClass   public void baseAfterClass()  { System.out.println("11 base  @AfterClass"); }
}

public class CheckoutTest extends BaseTest {
  @BeforeTest   public void checkoutTestTag()     { System.out.println("2 sub    @BeforeTest"); }
  @BeforeClass  public void checkoutClass()       { System.out.println("4 sub    @BeforeClass"); }
  @BeforeMethod public void checkoutMethod()      { System.out.println("6 sub    @BeforeMethod"); }

  @Test public void paysByCard() { System.out.println("7 test"); }

  @AfterMethod  public void checkoutAfterMethod() { System.out.println("8 sub    @AfterMethod"); }
  @AfterClass   public void checkoutAfterClass()  { System.out.println("10 sub   @AfterClass"); }
}

go deeper

for a junior

Remember the shape: within one scope, setup runs from the base class down and teardown from the subclass back up.

for a middle

Show that the scope ladder is applied before inheritance, and walk the full print order for a base class and subclass with hooks at several scopes.

for a senior

Diagnose ordering bugs: a subclass hook that silently overrides a same-named base hook, or two same-scope hooks in one class that someone assumed were ordered.

for a principal

Be ready to weigh how much setup a team lets accumulate in shared base classes, since every inherited hook runs for every subclass and hides ordering across files.

## Two orderings stacked on top of each other A TestNG test class often extends a shared base class that holds common setup, such as reading configuration or starting a browser. Both classes can declare configuration methods, the `@Before*` and `@After*` hooks from `org.testng.annotations`. Two separate rules then decide the order: 1. **The scope ladder**: suite, then `<test>` element, then class, then method on the way in, and the reverse on the way out. 2. **Inheritance order within one scope**: TestNG's documentation guarantees that `@Before` methods run in inheritance order, highest superclass first and then down the chain, and that `@After` methods run in reverse order, going back up the chain. The scope ladder is applied first. Inheritance only orders hooks **of the same scope**. A base class's `@BeforeMethod` therefore never runs before a subclass's `@BeforeClass`, however high in the hierarchy it is declared. ## The printed order for one test method Take `BaseTest` declaring `@BeforeSuite`, `@BeforeClass`, `@BeforeMethod`, `@AfterMethod` and `@AfterClass`, and `CheckoutTest extends BaseTest` declaring `@BeforeTest`, `@BeforeClass`, `@BeforeMethod`, `@AfterMethod` and `@AfterClass`, with a single test method. TestNG prints: 1. base `@BeforeSuite` 2. subclass `@BeforeTest` 3. base `@BeforeClass`, then subclass `@BeforeClass` 4. base `@BeforeMethod`, then subclass `@BeforeMethod` 5. the test method 6. subclass `@AfterMethod`, then base `@AfterMethod` 7. subclass `@AfterClass`, then base `@AfterClass` The suite-level and `<test>`-level hooks land where their scope puts them, regardless of which class in the hierarchy declares them. That is the trap in the "what prints first" puzzle: candidates who only learned "base first" put the base `@BeforeMethod` ahead of the subclass `@BeforeClass`. ## Why the reverse order on teardown matters Teardown climbing back up the chain mirrors setup coming down it. The subclass built on top of what the base class prepared, so the subclass must clean up first, while the base resources still exist. A typical example: - the base `@BeforeMethod` opens a session; - the subclass `@BeforeMethod` navigates to a page using that session; - the subclass `@AfterMethod` resets that page state, still needing the session; - the base `@AfterMethod` closes the session last. If teardown ran base first, the subclass teardown would find its session already closed. ## Things the guarantee does not cover | Situation | What TestNG promises | |---|---| | Base vs subclass hook, same scope | Base first for `@Before`, subclass first for `@After` (documented) | | Hooks of different scopes | Scope ladder decides; inheritance is irrelevant | | Two hooks of the same scope in one class | No documented order | | Subclass method with the same signature as a base hook | Java overriding applies: the base body does not run unless the override calls `super` | For two hooks of one scope in one class, do not rely on the order you happen to observe. Configuration annotations accept `dependsOnMethods`, so `@BeforeMethod(dependsOnMethods = "openSession")` makes the dependency explicit. Simpler still, merge them into one hook. For the override case, give base hooks names a subclass will not reuse by accident. A subclass that declares its own `setUp()` silently replaces the base logic, because invoking the base method on a subclass instance dispatches to the override. ## What it costs to put setup in a base class - A base-class hook runs for **every** subclass that inherits it, whether or not that class needs it. - The order of the setup a test receives is spread over several files, which is why ordering bugs appear when someone adds a hook to one level of the chain. - Changing a base hook from `@BeforeMethod` to `@BeforeClass` changes the state every subclass sees, not just one. Whether a shared base class is the right reuse mechanism at all is a framework-design question; here the subject is only how TestNG orders the hooks once the hierarchy exists. ## One base hook, many runs An inherited hook runs at its own scope **for each subclass**. If three test classes extend `BaseTest`, the base `@BeforeClass` runs three times, once before each subclass's test methods, because each class gets its own instance and its own class-level setup. A base `@BeforeSuite`, by contrast, still runs once for the whole suite. Candidates who picture a base class as one shared object are often surprised that its class-level setup repeats per subclass. ## Contrast with JUnit Jupiter JUnit Jupiter has its own hook annotations, its own inheritance rules and its own instance model, covered with that framework. When a candidate describes the TestNG order, the annotations named must be TestNG's: `@BeforeClass` and `@BeforeMethod`, not `@BeforeAll` and `@BeforeEach`, and the ordering guarantee quoted must be TestNG's documented one.

  • A TestNG subclass declares @BeforeMethod public void setUp() and so does its base class. What runs before each test?
    The two declarations share a signature, so the subclass method overrides the base one in Java. Invoking the base hook on a subclass instance dispatches to the override, so the base body does not run unless the override calls `super.setUp()`. Distinct hook names avoid that silent replacement.
  • Two @BeforeMethod hooks in the same TestNG class must run in a fixed order. How do you guarantee it?
    TestNG documents no order between same-scope hooks of one class, so make the dependency explicit: configuration annotations accept `dependsOnMethods`, as in `@BeforeMethod(dependsOnMethods = "openSession")`. Merging both into one hook is often clearer.

  • Subclass @Before hooks run before the superclass hooks of the same scope.
  • A base @BeforeMethod runs before a subclass @BeforeClass because base hooks come first.
  • @After hooks also run superclass first, then subclass.
  • TestNG ignores configuration methods declared in an abstract base class.
  • Two @BeforeMethod hooks in one class are guaranteed to run in source order.