0

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?

Florian
  • 4,821
  • 2
  • 19
  • 44
  • Ah, that explains a lot! `.getFields()` is on purpose. I'd be much happier if we'd be able to specify a public synthetic field. – Florian Aug 11 '22 at 10:59
  • I thought a lot, and the only way I could think of was to write the class in Kotlin (maybe Scala also works but I don't know Scala), but that means you would need to include the Kotlin runtime in your project, which is quite big :( – Sweeper Aug 11 '22 at 11:25

0 Answers0