Mockito ClassCastException - Mock 不能被投射
我在类中有一个方法,我想测试:AppleProcessor
public void process(Fruit fruit) {
if(fruit.getType() == Fruit.APPLE) {
fruitBasket.add(((AppleFruit) fruit).getApple());
}
else {
// do something else
}
}
请注意,Fruit是AppleFruit实现的方法的接口,并且还有一个方法。getType()
getApple()
我的测试如下所示:
@Mock
FruitBasket fruitBasket;
@Mock
Fruit fruit;
@Mock
AppleFruit apple;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAnAppleIsProcessed() {
AppleProcessor appleProcessor = new AppleProcessoer();
when(fruit.getType()).thenReturn(Fruit.APPLE);
when(((AppleFruit) fruit).getApple()).thenReturn(apple);
appleProcessor.process(fruit);
verify(fruitBasket).add(isA(Apple.class));
}
但是,我收到以下错误:
java.lang.ClassCastException: package.fruit.Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54 cannot be cast to package.fruit.AppleFruit
它来自测试中的这一行
when(((AppleFruit) fruit).getApple()).thenReturn(apple);
有人知道如何解决这个问题,以便我可以测试我的代码吗?