I'm getting an error: java.lang.ClassCastException: Z cannot be cast to java.lang.String
while trying to run coverage (EclEmma) on a Junit test. If I run the test regularly (without coverage) then it passes.
This is the code (all the fields in the class are Strings
):
@Override
public Map<String, String> getErrors() throws IllegalAccessException, IllegalArgumentException {
Map<String, String> errors = new HashMap<String, String>();
for (Field field : this.getClass().getDeclaredFields()) {
field.setAccessible(true);
String value = (String) field.get(this);
if (value.equals("N")) {
if (!errors.containsKey(field.getName())) {
errors.put(field.getName(), value);
}
}
}
return errors;
}
// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.
ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. So, for example, when one tries to cast an Integer to a String , String is not an subclass of Integer , so a ClassCastException will be thrown.
ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.
The problem is that to produce the code coverage EclEmma adds a field private static final transient boolean[] $jacocoData
to your class.
Since this field is only present during code coverage runs, the normal unit test passes, but the code coverage run fails: your original code is not expecting this non-String field.
The best solution is to check if the field you are seeing is really a String field and otherwise skipping the test of the field value:
for (Field field : this.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (field.getType() != String.class) {
continue;
}
String value = (String) field.get(this);
if (value.equals("N")) {
if (!errors.containsKey(field.getName())) {
errors.put(field.getName(), value);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With