模拟Mockito 2的最后一堂课 [英] Mock final class with Mockito 2
问题描述
我正在从我正在进行的项目中删除Powermock,所以我试图仅使用Mockito(mockito-core-2.2.28)重写一些现有的单一测试。
I'm removing Powermock from the project I'm currently working on, so I'm trying to rewrite some existing unitary test only with Mockito (mockito-core-2.2.28).
当我运行测试时,出现以下错误:
When I run the test, I have the following error:
org.mockito.exceptions.base.MockitoException :
org.mockito.exceptions.base.MockitoException:
无法模拟/间谍类com.ExternalpackagePath.Externalclass
Cannot mock/spy class com.ExternalpackagePath.Externalclass
Mockito无法模拟/间谍因为:
Mockito cannot mock/spy because :
- final class
我知道这个问题已被提出(如何模拟与mockito进行的最后一课,模拟对象调用final使用Mockito对静态方法进行分类),但我没有找到我正在寻找的答案。
I know that this question has already been asked (How to mock a final class with mockito, Mock objects calling final classes static methods with Mockito), but I didn't find the answer I'm looking for.
以下是我的代码摘录:
public class MyClassToTest extends TestCase {
private MyClass myClass;
@Mock private Externalclass ext; // This class is final, I would like to mock it
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
ext = Mockito.mock(Externalclass.class);
}
}
如Mockito文档中所述( https://github.com/mockito/mockito/wiki/What%27s -new-in-Mockito-2 ,§Mockthe unockockable),我添加了org.mockito.plugins.MockMaker文件。这是我项目的树:
As mentioned in the Mockito documentation (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2, §Mock the unmockable), I added the org.mockito.plugins.MockMaker file. This is the tree of my project :
- 项目
- src
- com.packagePath.myPackage
- myClass
- com.packagePath。 myPackage
- myClassToTest
- mockito-extensions
- org.mockito.plugins.MockMaker
我还尝试将resources目录放在src中,在一个名为test的子目录中,但结果仍然相同。
I also tries to put the "resources" directory in "src", in a subdir called "test", but the result is still the same.
我认为用Mockito v2嘲笑决赛是可能的。有人知道这里缺少什么吗?
I thought that mocking a final was possible with Mockito v2. Does someone have an idea of what is missing here ?
谢谢!
推荐答案
嗯,我发现这里有什么问题,对其他人来说可能有用。我的项目树是错误的,我将org.mockito.plugins.MockMaker直接放在src中的mockito-extension目录中。这是我的树现在:
Well, I found what's wrong here, it maybe useful for other people. My project tree is wrong, I put the org.mockito.plugins.MockMaker in a directory "mockito-extension" directly in "src". This is my tree now:
- 项目符号
- src
- com.packagePath.myPackage
- myClass
- org.mockito.plugins.MockMaker
- com.packagePath.myPackage
- myClassToTest
这篇关于模拟Mockito 2的最后一堂课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- com.packagePath.myPackage
- src
- com.packagePath.myPackage
- src