我在类中有一个方法 AppleProcessor
我想测试一下:
public void process(Fruit fruit) {
if(fruit.getType() == Fruit.APPLE) {
fruitBasket.add(((AppleFruit) fruit).getApple());
}
else {
// do something else
}
}
请注意,Fruit 是一个带有方法 getType()
的接口,AppleFruit 实现了该方法,并且还有一个 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);
谁知道如何解决这个问题以便我测试我的代码?
原文由 user2844485 发布,翻译遵循 CC BY-SA 4.0 许可协议
当你说
你告诉 Mockito:
fruit
变量应该是Fruit
的一个实例。 Mockito 将动态创建一个实现Fruit
的类(此类是Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54
),并创建此类的实例。此类没有理由成为AppleFruit
的实例,因为您没有告诉 Mockito 该对象必须是 AppleFruit 类型。声明为
AppleFruit
,类型为AppleFruit
。