Writing Parameterized Tests with JUnit Rules

I can’t help repeating myself: JUnit Rules are among the best, maybe the best, feature of JUnit. I even gave a talk at Devoxx about Junit Rules.

The great thing about Rules compared to other options to solve similar problems like TestRunners or common super classes is that you can combine multiple Rules. One favorite example why you want to do this are Parameterized Tests they are nice, but what if you want to parameterize Tests build on the base of the Spring JUnit Test Runner. It doesn’t work, because you can have only one Test Runner.

The problem with this example is: There aren’t replacements (as far as I know) for the two runners with Rules. The Spring Runner should be replaceable in principle, but it seems to be not as easy as one might think.

But when I was preparing my Devoxx talk it occurred to me that you can actually do Parameterized Tests using Rules! And I think the usage is actually more intuitive then Parameterized tests with its custom annotations and stuff.

It looks like this:

  1. public class SimpleExampleTest {
  2.  
  3.     @Rule
  4.     public Generator<String> params =
  5.         new ListGenerator(asList("alpha", "beta", "gamma"));
  6.  
  7.     @Test
  8.     public void testSomething() throws Exception {
  9.         assertTrue(params.value().length() >= 4);
  10.     }
  11. }

You just specify a ListGenerator rule, with all the values you want to run your tests with. Each test in the class gets executed once for each parameter value provided, and it can access the parameter value using the value() method of the rule. I think with the current feature set available for Java and JUnit it doesn’t get much easier to read and write.

The rule itself uses an ErrorCollector to gather test failures so if tests fail you’ll see all the failures not just the last one or something.

The code for Parameterized JUnit Tests with Rules is available at GitHub. Just keep in mind, it is an experiment and demonstration of concept I hacked together at Devoxx.


Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter