@BeforeMethod and inheritance - order of execution (TestNG)

ecbrodie picture ecbrodie · Dec 29, 2013 · Viewed 7k times · Source

My question is basically the same as this SOF question, but deals with @BeforeMethod instead of @BeforeClass for TestNG.

Does test class inheritance play a factor when determining the order that @BeforeMethod annotated methods will execute? 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) or will the child's run before the parent, or does the order depend on some other factor such as alphabetical order of the method name. I'm trying to see if there is an inheritance order that I can rely on instead of having to use parameters of the annotation such as dependsOnMethods.

Answer

sleske picture sleske · Oct 10, 2016

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.