Mockito ClassCastException - A mock cannot be cast

When you say

@Mock
Fruit fruit;

You tell Mockito: the fruit variable should be an instance of Fruit. Mockito will dynamically create a class which implements Fruit (this class is Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54), and create an instance of this class. There's no reason for this class to be an instance of AppleFruit, since you didn't tell Mockito that the object had to be of type AppleFruit.

Declare it as AppleFruit, and it will be of type AppleFruit.


To anyone searching for this just include:

@Mock(extraInterfaces = {AppleFruit.class})
Fruit fruit;

Which will add an extra interface to the mock and the casting wont raise any exceptions.