Iterating over an array of Enum classes in Java, testing the `parse ()` method of each

I am trying to be effective in writing some Junit tests for my Java Enum classes and method testing parse()for each. Here's an example of doing this one at a time 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 method parse(), I would prefer not to write the same code for each of them, replacing the class name wherever it was found.

I would like to do something more:

@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.

Does anyone know if there is an easy way?

+4
source share
3 answers

" " - :

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))
);

parse :

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

+2

t.getEnumConstants(),

@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);
        }
    }
}

, , Generic ( , ), .parse().

+1

Source: https://habr.com/ru/post/1686048/


All Articles