What order are the Junit @Before/@After called?
Yes, this behaviour is guaranteed:
@Before
:
The
@Before
methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.
@After
:
The
@After
methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.
One potential gotcha that has bitten me before:
I like to have at most one @Before
method in each test class, because order of running the @Before
methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest()
.
But, although @Before
is documented as The @Before methods of superclasses will be run before those of the current class. No other ordering is defined.
, this only applies if each method marked with @Before
has a unique name in the class hierarchy.
For example, I had the following:
public class AbstractFooTest {
@Before
public void setUpTest() {
...
}
}
public void FooTest extends AbstractFooTest {
@Before
public void setUpTest() {
...
}
}
I expected AbstractFooTest.setUpTest()
to run before FooTest.setUpTest()
, but only FooTest.setupTest()
was executed. AbstractFooTest.setUpTest()
was not called at all.
The code must be modified as follows to work:
public void FooTest extends AbstractFooTest {
@Before
public void setUpTest() {
super.setUpTest();
...
}
}