Search code examples
javajunit5

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.       

Solution

  • If you really want to trigger it

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