为什么 Junit 抛出 java.lang.ClassCastException 即使 类 兼容并且在 java 代码中工作正常
Why Junit throws java.lang.ClassCastException even if classes are compatible and works fine in java code
我有 class 辆汽车和 class 辆汽车。
Car 扩展了 Vehicle。
当我为下面的方法编写 junit 时,它给出了 class 转换异常。
上型铸造线。
void method(){
// some code
Car a = (Car)Vehicle;
// some code
}
它抛出异常
java.lang.ClassCastException: com.abc.Vehicle 无法转换为 com.abc.Car
Upcasting 始终是一个密码,应该避免。通常需要它,因为代码设计违反了告诉,不要问!原则。
只是猜测:
在您的情况下,"procution code" 始终传递 class A
的实例,以便它起作用。但是你的测试显然设置了一个 class B
对象(在某些时候你没有显示)无法转换为 A
.
我有 class 辆汽车和 class 辆汽车。 Car 扩展了 Vehicle。
当我为下面的方法编写 junit 时,它给出了 class 转换异常。 上型铸造线。
void method(){
// some code
Car a = (Car)Vehicle;
// some code
}
它抛出异常 java.lang.ClassCastException: com.abc.Vehicle 无法转换为 com.abc.Car
Upcasting 始终是一个密码,应该避免。通常需要它,因为代码设计违反了告诉,不要问!原则。
只是猜测:
在您的情况下,"procution code" 始终传递 class A
的实例,以便它起作用。但是你的测试显然设置了一个 class B
对象(在某些时候你没有显示)无法转换为 A
.