問題描述
我正在從我目前正在處理的項目中刪除 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 :
- 最后一節課
我知道這個問題已經被問過了(如何模擬帶有 mockito 的 final 類,模擬對象調用 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,§Mock the unmockable),我添加了 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 :
- 項目
- 源代碼
- com.packagePath.myPackage
- 我的班級
- com.packagePath.myPackage
- myClassToTest
- 模擬擴展
- org.mockito.plugins.MockMaker
我也嘗試將資源"放在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:
- 項目
- 源代碼
- com.packagePath.myPackage
- 我的班級
- org.mockito.plugins.MockMaker
- com.packagePath.myPackage
- myClassToTest
這篇關于使用 Mockito 2 模擬最終課程的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!
- com.packagePath.myPackage
- 源代碼
- com.packagePath.myPackage
- 源代碼