@BeforeMethod and inheritance - order of execution (TestNG)

If I have class A and a class B extends A and both have one @BeforeMethod method, then will the parent's (A) run before the child's (B) [...]

Yes, they will.

@BeforeMethod methods will run in inheritance order - the highest superclass first, then going down the inheritance chain. @AfterMethod methods run in reverse order (up the inheritance chain).

Note, however, that the ordering of multiple annotated methods within one class is not guaranteed (so it's best to avoid that).


Reading the code, this seems to have been the case in all versions of TestNG, however it was only documented in October 2016:

The annotations above will also be honored (inherited) when placed on a superclass of a TestNG class. This is useful for example to centralize test setup for multiple test classes in a common superclass.

In that case, TestNG guarantees that the "@Before" methods are executed in inheritance order (highest superclass first, then going down the inheritance chain), and the "@After" methods in reverse order (going up the inheritance chain).

See documentation-main.html on GitHub, or the online documentation.

Disclaimer: It was me who wrote and submitted this addition to the docs.


As explained in the other answers, TestNG will consider inheritance for execution order.

If you prefer to make the order of the "Before" methods explicit, you can also have the child simply call the parent setup.

public class ChildTest extends ParentTest {

    @BeforeMethod
    public void setup() {
       super.setup();
       // Child setup code follows here.
    }
}

public class ParentTest {
    @BeforeMethod // Only need if test will ever be invoked directly
    public void setup() {
      // Parent setup goes here.
    }
}

Tags:

Java

Testng