DaDaDom DaDaDom - 6 months ago 65
Java Question

@BeforeClass and inheritance - order of execution

I have an abstract basis class, which I use as a basis for my unit tests (TestNG 5.10). In this class I initialize the whole environment for my tests, setting up database mappings, etc. That abstract class has a method with a

@BeforeClass
annotation which does the initialization.
Next thing, I extend that class with specific classes in which I have
@Test
methods and also
@BeforeClass
methods. These methods do class-specific initialization of the environment, e.g. put some records into the database.

My question is how I can enforce a specific order of the @BeforeClass annotated methods. I need the ones from the abstract base class to be executed before the ones of the extending class.

Example:

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

class B extends A {
@BeforeClass
doSpecificInitialization() {...}

@Test
doTests() {...}
}


Expected order:

A.doInitialization
B.doSpecificInitialization
B.doTests


Actual order:

B.doSpecificInitialization // <- crashes, as the basic init is missing
(A.doInitialization // <---not executed
B.doTests) // <-/

Answer

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.

Comments