helpermethod helpermethod - 1 year ago 91
Java Question

Junit - Multiple @Before vs. one @Before split up into methods

In a unit test, I need to perform a quite complex setup (this may be a code smell but this is not what this question is about :-)). What I'm interested in is if it is better to have multiple

methods performing the setup or just one, which calls helper methods to perform the initialization.


public void setUpClientStub() {


public void setUpObjectUnderTest() {



public void setUp() {

Answer Source

As has been said in other responses, the order in which JUnit finds methods is not guaranteed, so the execution order of @Before methods can't be guaranteed. The same is true of @Rule, it suffers from the same lack of guarantee. If this will always be the same code, then there isn't any point in splitting into two methods.

If you do have two methods, and more importantly, if you wish to use them from multiple places, then you can combine rules using a RuleChain, which was introduced in 4.10. This allows the specific ordering of rules, such as:

public static class UseRuleChain {
  public TestRule chain= RuleChain
               .outerRule(new LoggingRule("outer rule"))
               .around(new LoggingRule("middle rule"))
               .around(new LoggingRule("inner rule"));

  public void example() {

This produces:

starting outer rule
starting middle rule
starting inner rule
finished inner rule
finished middle rule
finished outer rule

So you can either upgrade to 4.10 or just steal the class.

In your case, you could define two rules, one for client setup and one for object, and combine them in a RuleChain. Using ExternalResource.

public static class UsesExternalResource {
  private TestRule clientRule = new ExternalResource() {
      protected void before() throws Throwable {

      protected void after() {

  @Rule public TestRule chain = RuleChain

So you'll have the following execution order:

the test