Jens Schauder is software developer since 1997. He loves software development for the constant challenges and constantly changing environment. A great chance to learn and teach. He is also blogger, author of various articles and speaker at conferences. Jens is a DZone MVB and is not an employee of DZone and has posted 75 posts at DZone. You can read more from them at their website. View Full User Profile

Writing Parameterized Tests with JUnit Rules

12.21.2012
| 2446 views |
  • submit to reddit

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:

    public class SimpleExampleTest {
     
        @Rule
        public Generator<String> params =
            new ListGenerator(asList("alpha", "beta", "gamma"));
     
        @Test
        public void testSomething() throws Exception {
            assertTrue(params.value().length() >= 4);
        }
    }

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.

Published at DZone with permission of Jens Schauder, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: