Hierarchical Context Runner for JUnit

Stefan Bechtold <[email protected]> Thu, 31 Oct 2013 19:18:51 +0100
Newsgroups gmane.comp.java.junit.user
Message-ID <[email protected]>
Hi folks

I investigated some time to come up with a new Runner for JUnit and I would like to get feedback and your input about it. The runner aims on test hierarchies, i.e. tests that can be grouped into contexts for better readability. You can compare this with the contexts in rspec and I would say it is an enhancement of the Enclosed Runner.

Let's start with an example:

@RunWith(HierarchicalContextRunner.class)
public class BankAccountTest {
  private Account account;

  public class SavingsAccountContext {
    @Before
    public void setup() {
      myAccount = new SavingsAccount();
    }

    @Test
    public void accountWithBalanceOf100_earns3InInterest() throws Exception {
      myAccount.setBalance(100.0);
      assertThat(myAccount.getInterestEarned(), is(closeTo(3.0, 0.001)));
    }

    @Test
    public void accountWithBalanceOf200_earns6InInterest() throws Exception {
      myAccount.setBalance(200.0);
      assertThat(myAccount.getInterestEarned(), is(closeTo(6.0, 0.001)));
    }
  }

  public class MoneyMarketAccountContext {
    @Before
    public void setup() {
      myAccount = new MoneyMarketAccount();
    }

    @Test
    public void accountWithBalanceOf100_earns4InInterest() throws Exception {
      myAccount.setBalance(100.0);
      assertThat(myAccount.getInterestEarned(), is(closeTo(4.0, 0.001)));
    }

    @Test
    public void accountWithBalanceOf200_earns8InInterest() throws Exception {
      myAccount.setBalance(200.0);
      assertThat(myAccount.getInterestEarned(), is(closeTo(8.0, 0.001)));
    }
  }
}

(This example is copied from the newest video of Robert Martin from his website http://www.cleancoders.com, video 22 - Test Process, starting at 00:32:38)

Key points to note:

1. There are no static classes that contain tests.
2. There are no extends statements, hierarchies are created by creating inner classes (nice syntax).
3. Each context can access all variables of the parent context.
4. @Rule, @Before and @After annotations are run for the complete hierarchy of a test (not visible from the example)
5. Mostly all features of the BlockJUnit4ClassRunner are also supported.

Another example can be found on my github.org page at https://github.com/bechte/junit-hierarchicalcontextrunner/wiki.

For me, this runner closes a gap of missing ability of the JUnit framework to support hierarchies.

I am really looking forward to getting some feedback on this runner.

All the best

Bechte

-- 

Stefan Bechtold

eCard: http://ecard.bechte.de/

http://www.bechte.de, http://twitter.com/bechte 



[Non-text portions of this message have been removed]