One of our classes uses reflection to list another class's fields:
public List<String> getFieldNames(Class clazz) {
List<String> result = new ArrayList<>();
var fields = clazz.getFields();
for (Field field : fields) {
var encodedName = encodeName(field.getName());
result.add(encodedName);
}
return result;
}
This code breaks in JaCoCo and PIT mutation tests. Their test setups add a synthetic field to clazz
. Our encodeName
method cannot digest that field's name.
We will therefore ignore synthetic fields:
for (Field field : fields) {
if (!field.isSynthetic()) {
// ...
}
}
To be safe, we'd like to write a unit test for this new if
condition. The test should call getFieldNames
with a class with a synthetic field and assert that the return value includes only the non-synthetic fields.
What's the easiest and most reliable way to create a Class with a synthetic field?
Answers to the question How to create synthetic fields in java? suggest that specifying an inner class within our test class should do the job, but apparently this adds a private synthetic field, and .getFields() doesn't consider it. Is there a way to create a public synthetic field?