@BeforeClass and inheritance - order of execution

edit: Answer below is for JUnit, but I will leave it here anyway, because it could be helpful.

According to the JUnit api: "The @BeforeClass methods of superclasses will be run before those the current class."

I tested this, and it seems to work for me.

However, as @Odys mentions below, for JUnit you need to have the two methods named differently though as doing otherwise will result in only the subclass method being run because the parent will be shadowed.


Don't put the @BeforeClass on the abstract class. Call it from each subclass.

abstract class A {
    void doInitialization() {}
}

class B extends A {
    @BeforeClass
    void doSpecificInitialization() {
        super.doInitialization();
    }

    @Test
    void doTests() {}
}

Seems like TestNG has @BeforeClass(dependsOnMethods={"doInitialization"}) - give it a try.


I added public to the abstract class and TestNG (6.0.1) executed the doInitialization() before doTests. TestNG does not execute doInitialization() if I remove public from class A.

public abstract class A {
 @BeforeClass
 doInitialization() {...}
}

class B extends A {    
 @Test
 doTests() {...}
}

I just tried your example with 5.11 and I get the @BeforeClass of the base class invoked first.

Can you post your testng.xml file? Maybe you are specifying both A and B there, while only B is necessary.

Feel free to follow up on the testng-users mailing-list and we can take a closer look at your problem.

-- Cedric