Mockito ClassCastException - 无法投射模拟

Mockito ClassCastException - A mock cannot be cast(Mockito ClassCastException - 无法投射模拟)
本文介绍了Mockito ClassCastException - 无法投射模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想测试 AppleProcessor 类中有一个方法:

I have a method in the class AppleProcessor which I would like to test:

public void process(Fruit fruit) {
    if(fruit.getType() == Fruit.APPLE) {
        fruitBasket.add(((AppleFruit) fruit).getApple());
    }
    else {
        // do something else
    }
}

注意,Fruit 是 AppleFruit 实现的方法 getType() 的接口,并且还有一个 getApple() 方法.

Note that Fruit is an interface with the method getType() which AppleFruit implements and also has a getApple() method.

我的测试看起来像:

@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 无法转换为 package.fruit.AppleFruit

来自测试中的这一行

when(((AppleFruit)fruit).getApple()).thenReturn(apple);

有人知道如何解决这个问题,以便我可以测试我的代码吗?

Would anyone know how to resolve this so I can test my code?

推荐答案

当你说

@Mock
Fruit fruit;

你告诉 Mockito:fruit 变量应该是 Fruit 的一个实例.Mockito会动态创建一个实现Fruit的类(这个类是Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54),并创建这个类的一个实例.这个类没有理由成为 AppleFruit 的实例,因为您没有告诉 Mockito 该对象必须是 AppleFruit 类型.

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.

将其声明为AppleFruit,其类型为AppleFruit.

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

这篇关于Mockito ClassCastException - 无法投射模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)