[Solved] Why Junit throws java.lang.ClassCastException even if classes are compatible and works fine in java code


Upcasting is always a codesmell and should be avoided. Usually it is needed because the code design violated the Tell, don’t ask! principle.

Just guessing:
In your case the “procution code” always passes instaces of class A so that it works. But your test obviously sets up a class B object (at some point you didn’t show) which fails to be casted to A.

1

solved Why Junit throws java.lang.ClassCastException even if classes are compatible and works fine in java code