如何触发 ClassCastException?我正在尝试对 class 进行单元测试,但有一个 try/catch 片段我无法检查

How to Trigger a ClassCastException? I'm trying to unit test a class and there is this try/catch segment which i'm not able to check

public int compare(Cat cat1, Cat cat2) {

        try {
            Cat obj1 = cat1;
            Cat obj2 = cat2;
            return obj1.getCode().compareTo(obj2.getCode());
            //compareTo returns 0/1, getCode returns a string color of cat.
        } 
        catch (ClassCastException e) {
            throw new CatRuntimeException("Comparison failed.");
        }
}
 //want to test the catch part.       

您希望以导致异常的方式调用该函数,然后检查它是否被抛出。这里有一个 link 可能会有帮助:https://www.baeldung.com/junit-assert-exception

如果你真的想触发它

Cat c1 = mock(Cat.class);
Cat c2 = mock(Cat.class);
when(c1.getCode()).thenThrow(new ClassCastException());
yourObject.compare(c1, c2);