@BeforeMethod and Inheritance - Execution Order (TestNG)

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

Is inheritance of the test class a factor determining the execution order of @BeforeMethod annotated methods? If I have class A, and class B extends A, and both have the same @BeforeMethod method, then the parent (A) starts in front of the child (B) or the child process will run in front of the parent or another factor, such as alphabetical, depends on the order method name order. I'm trying to figure out if there is an inheritance order that I can rely on, instead of using annotation options like dependOnMethods.

+8
java testng
source share
3 answers

If I have class A and class B extends A, and both have the same @BeforeMethod method, then parent (A) is run before the child (B) [...]

Yes they will.

@BeforeMethod methods will be executed in the order of inheritance - first in the upper superclass, then in the inheritance chain. @AfterMethod works in reverse order (up the inheritance chain).

Note, however, that ordering multiple annotated methods within the same class is not guaranteed (therefore, it is best to avoid this).


Reading the code seems to have occurred in all versions of TestNG, however it was only registered in October 2016:

The annotations above will also be honored (inherited) when you place the superclass of the TestNG class. This is useful, for example, to centralize the installation of a test for several test classes in a common superclass.

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

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

Disclaimer: It was I who wrote and sent this supplement to the documents.

+2
source share

This happens in JUnit, but not TestNG. However, you can simply specify the parent setting for the child.

 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. } } 
0
source share

An order has nothing to do with class inheritance.

You can try setting the priority attribute in the @Test annotation. If no parameters are specified in the annotation, they are performed in alphabetical order.

You also prefix the methods according to the order you want to execute (e.g. 01_method1() , 02_method2() ).

-one
source share

All Articles