JUnit: Rules

JUnit has a nice feature now: Rules.
While I don’t like every detail of the implementation, they are basically a very good thing.

This is a short introduction how to use them…

What are rules

Rules are basically wrappers around test methods. They offer a nice way to prepare before a test run and clean up afterwards.
Basically they replace that awful setup/tearDown method stuff…

How to use them

Just create a public (non-static) field for the rule. And add the annotation @Rule.

Example

One of my favorite rules is TemporaryFolder. That rule creates a temporary folder and an easy way to create files and folders…

public class RulesTest {
@Rule
public TemporaryFolder tmp = new TemporaryFolder();

@Test
public void testIt() throws IOException {
  System.out.println( "Creating tmp folder @ " + tmp.newFolder( "aFolder" ).getAbsolutePath() );
  assertTrue( tmp.newFile( "a file" ).exists() );
}
}

The output of this test is (at least on my system):

Creating tmp folder @ /tmp/junit8120700871928645940/aFolder

What to do now?

1. Create a template for your IDE that adds the rule field…

It really is worth it. Please. I know the human being tries to avoid the initial setup costs (of maybe 3 minutes) and prefers to type the same lines several hundred times…

2. Enjoy writing Unit tests (again)

No more long and ugly setup/tearDown methods. No more files accidentally left in the tmp folder…

In the next posts I will show you some more rules that I find very useful….


2 Responses to “JUnit: Rules”

  • oppjinx Says:

    Interesting. I am just wondering if you can enlighten me when setUp/tearDown is awful?

  • johannes Says:

    Take the above example:
    Creating setup/tearDown methods that prepare temporary files and folders (and clean them up again) needs a lot of work (at least a couple of lines and one field)…

    Repeating that code over and over again seems to be a bad idea…

Leave a Reply