Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@BeforeMethod and inheritance - order of execution (TestNG)

Tags:

java

testng

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.

like image 909
ecbrodie Avatar asked Dec 29 '13 14:12

ecbrodie


2 Answers

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.

like image 139
sleske Avatar answered Sep 20 '22 07:09

sleske


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.
    }
}
like image 25
James Gawron Avatar answered Sep 21 '22 07:09

James Gawron