Archive for July, 2009

JUnit 4.7RC-1 Rules

Saturday, July 25th, 2009

Having come across JUnit 4.7: Per-Test rules on Info-Q I was keen to have a look at this new feature of JUnit. So I downloaded the latest release candidate and installed it locally. You can get the release candidate from Kent Beck’s github repository.

To start with I begun reading Kent Beck’s blog entry about Inteceptors in JUnit which was originally written prior to the renaming of Inteceptors to Rules.

I begun by creating the simple example LoggingRule which is reproduced below. This rule extends the TestWatchman base class to simply print out messages when a method starts, fails, succeeds or finishes. Nothing too exciting about that…

import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;

public class LoggingRule extends TestWatchman {

  @Override
  public void failed(Throwable e, FrameworkMethod method) {
    System.out.println(method.getName() + " failed");
  }

  @Override
  public void finished(FrameworkMethod method) {
    System.out.println(method.getName() + " finished");
  }

  @Override
  public void starting(FrameworkMethod method) {
    System.out.println(method.getName() + " starting");
  }

  @Override
  public void succeeded(FrameworkMethod method) {
    System.out.println(method.getName() + " succeeded");
  }
}

In order to then use this LoggingRule in a test you justĀ  add the @Rule annotation to the a LoggingRule property in a test case. Below is the not too exciting test case I created to see the LoggingRule in action.

import static org.junit.Assert.assertNotNull;

import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;

public class JUnitRulesSandbox {

  @Rule
  public LoggingRule log = new LoggingRule();

  @Test
  public void testLoggingRule() throws IOException {
    System.out.println("Testing Logging Rule");
    assertNotNull(log);
  }
}

When the test is run the following gets output to the console.

testLoggingRule starting
Testing Logging Rule
testLoggingRule succeeded
testLoggingRule finished

As can be seen the LoggingRule is called when the method testLoggingRule is starting, has succeeded and finishes.

Nothing complex or too exciting so far, but a start to understanding Rules in JUnit. The LoggingRule was simple to implement thanks to the base implementation TestWatchman. Next up I want to look closer at TestWatchman and the currently provided Rules, before trying a more complex custom implementation myself.