Junit4: @BeforeClass of superclass is not executed

Created on 6 Mar 2012  ·  7Comments  ·  Source: junit-team/junit4

Contrary to the statement in @BeforeClass annotation javadoc :
/** The @BeforeClass methods of superclasses will be run before those the current class. */
The @BeforeClass annotated method of superclass is not called if there is another @BeforeClass is subclass.

public abstract class SuperTest {
    @BeforeClass
    public static void beforeClass() throws Exception {
        fail("why don't you call me ?");    // never fails
    }
}

public class MyTestA extends SuperTest {
    @BeforeClass
    public static void beforeClass() {
        fail("Thanks for calling");     // fails here
    }

    @Test
    public void test() {
        fail("Failure expected from MyTestA.beforeClass()");  
    }
}

public class MyTestB extends SuperTest {
    @BeforeClass
    public static void beforeClass() {
    }

    @Test
    public void test() {
        fail("Failure expected from SuperTest.beforeClass()");    // fails here
    }
}

Most helpful comment

The method in the superclass is shadowed by the method with the same name in the subclass. If you give the @BeforeClass methods different names, they will run in the correct order.

All 7 comments

The method in the superclass is shadowed by the method with the same name in the subclass. If you give the @BeforeClass methods different names, they will run in the correct order.

thanks taral, issue is settled then. A little mention in the javadoc of @BeforeClass could be helpful though.

I learnt the same thing the hard way. As @gonzen has said a little mention in javadoc could help us avoid the situation altogether. If it makes sense I can add it in the javadoc and submit a patch.

@amalakar, a javadoc patch would definitely be appreciated!

Here is the pull request: https://github.com/KentBeck/junit/pull/504

Me too.

I with there was some big note on: http://junit.sourceforge.net/javadoc/org/junit/Before.html saying that you should see http://junit.org/javadoc/latest/ instead, + a link to the new docs from the readme.

Was this page helpful?
0 / 5 - 0 ratings