Iterate Over Array of Enum Classes in Java, Testing `parse()` Method of Each

Viewed 675

I'm trying to be efficient in writing some Junit tests for my Java Enum classes, and testing the parse() method of each. Here's an example of doing it one at a time for the FileFormatCodeEnum:

@Test
public void testFileFormatCodeEnum() {

    FileFormatCodeEnum[] ens = FileFormatCodeEnum.values();
    for(FileFormatCodeEnum en : ens) {
        Assert.assertEquals(FileFormatCodeEnum.parse(en.getValue()), en);
    }
}

Since every Enum class in my project has a parse() method, I'd prefer not to write this same code for every one of them by replacing the class name everywhere it's found.

I'd like to do something more like this:

@Test
public void testAllEnums() {
    ArrayList<Class> allEnums = new ArrayList<Class>();
    allEnums.add(FileFormatCodeEnum.class);
    allEnums.add(RoleTypeCodeEnum.class);

    //begin some pseudo-code here
    for (Class clazz : allEnums) {
        //TODO: get clazz.values() of the enum into an array named 'ens'
        for(Generic en : ens) {
            //cast the generic enum to a specific enum type maybe?
            //then execute the parse method on the specific enum
            Assert.assertEquals(SpecificEnum.parse(en.getValue()), en);
        }
    }
}

I'm not quite sure how to use reflection (?) to achieve this.

Anyone know if there's a simple way?

3 Answers

Make a class to store a "test pair" - the list of all enums, and a function to parse their textual values:

class TestEnum {
    private final List<Enum> values;
    private final Function<String,Enum> parse;
    public TestEnum(List<Enum> v, Function<String,Enum> p) {
        values = v;
        parse = p;
    }
    public List<Enum> getValues() { return values; }
    public Function<String,Enum> getParse() { return parse; }
}
List<TestEnum> allEnums = Arrays.asList(
    new TestEnum(Arrays.asList(FileFormatCodeEnum.values()), s -> FileFormatCodeEnum.parse(s))
,   new TestEnum(Arrays.asList(RoleTypeCodeEnum.values()), s -> RoleTypeCodeEnum.parse(s))
);

Now you can go through all enums and test their parse method like this:

for (TestEnum t : allEnums) {
    for (Enum v : t.getValues()) {
        Assert.assertEquals(t.getParse().apply(v.toString()), v);
    }
}

Demo.

You could use t.getEnumConstants(), as per this other question

@Test
public void testAllEnums() {
    ArrayList<Class> allEnums = new ArrayList<Class>();
    allEnums.add(FileFormatCodeEnum.class);
    allEnums.add(RoleTypeCodeEnum.class);

    //begin some pseudo-code here
    for (Class<Generic> clazz : allEnums) {
        for(Generic en : clazz.getEnumConstants()) {
            Assert.assertEquals(SpecificEnum.parse(en.getValue()), en);
        }
    }
}

Of course, the code above supposes the enums implement the Generic interface (or whatever interface you may want to use), and that this interface has a .parse() method.

Related