Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

java - @BeforeClass and inheritance - order of execution

I have an abstract base class, which I use as a base for my unit tests (TestNG 5.10). In this class, I initialize the whole environment for my tests, setting up database mappings, etc. This abstract class has a method with a @BeforeClass annotation which does the initialization.

Next, 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).

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 base init is missing
(A.doInitialization        // <---not executed
 B.doTests)                // <-/
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...