The beauty of JUnit Theories

I’m beginning to appreciate the beauty and elegance of JUnit theories as included in JUnit 4.5 and above. 

JUnit theories allow you to easily test code using multiple data points. Much like the name suggests it treats code as “theory” that you are trying to prove. You can also reuse the same data points to test multiple functions. You can even use the Cartesian product of multiple data-points, if that fits your code.

If you have multiple methods annotated with @Theory, each of these methods will be called for each data-point. This has enormous power. I tend to hate writing tests generally, but with theories, writing tests feels so much more effective.

You can use the following annotations to configure your theories:

  • @Theory - annotates the test methods (instead of @Test)
  • @RunWith(Theories.class) - annotate the class to use JUnit theories
  • @DataPoint - annotates a public static single data-point
  • @DataPoints - a public static method returning multiple data-points

Here’s another great post on junit theories. For a great example of using JUnit theories, check out dollar