An endpoint that my application interacts with allows you to specify which fields are returned in the JSON result. My application will then map the JSON to a POJO using Jackson. Quite often I add more fields in one place and forget to add it in the other which results in problems. I wrote a unit test to help make the process easier but I feel like there could be room for improvements.
Here's what I have so far:
private static final String[] POTENTIAL_FIELDS = new String[] { "field1", "field2" };
@Test
public void checkFields() {
// get all constant fields
Set<String> constantFields = Arrays.stream(POTENTIAL_FIELDS)
.map(String::toLowerCase)
.collect(Collectors.toSet());
// get all private fields
Set<String> reflectFields = Arrays.stream(FieldsModel.class.getDeclaredFields())
.filter((field) -> !Modifier.isStatic(field.getModifiers()))
.map(field -> field.getName().toLowerCase())
.collect(Collectors.toSet());
Set<String> symmetricDifference = Sets.symmetricDifference(constantFields, reflectFields);
// check if there's a difference
if (!symmetricDifference.isEmpty()) {
Assert.fail(String.format("Difference: %s\n", String.join(",", symmetricDifference)));
}
}
private static class FieldsModel {
private int field1;
private String field2;
}
The only non-standard imports are FieldsModel
which is what the name suggests, and Sets
which is from Guava (com.google.coom.collect.Sets
). Here is a direct link to the method I used.