Since testing is so much fun, I decided to unit-test my enums too. Just in case someone (me) changes those values without telling anybody or whatever reason for testing you got. Suppose you have an enum like follows:
public enum Month {
January,
February,
...
December;
}
To test that you could just use the valueOf(String) method of any enumeration and see if the resulting object is null or not. So you would call
assertThat(Month.valueOf("January"), is(notNullValue()));
for every item in the enumeration and probably create different test methods for each of those calls. Instead of that you could also use parameterized tests (with @RunWith(Parameterized.class) annotation) but I don’t like constructors in test classes. So with the release of JUnit 4.5 we now got Theories which are similar but not the same as parameterized tests. Instead of parameters and constructors with private fields you use data points and that’s it basically. With that we can replace all those more or less similar test cases for every enumeration item with a single:
@Theory
public final void monthIsNotNull(final String month) {
assertThat(Month.valueOf(month), is(notNullValue()));
}
What’s missing here is the already mentioned DataPoint. You declare one with the @DataPoint annotation or multiple data points with the @DataPoints annotation like follows:
@DataPoint public static final String JANUARY = "January"
After that you have to annotate your test class with the @RunWith(Theories.class) and JUnit will automatically run the theory on all available data points. You can take a look here to see how I applied that to unit-testing inside the Denove-core package.