![](/img/trans.png)
[英]Android : Mockito (2.0.2-beta) - Cannot mock/spy final classes
[英]Android Instrumented Test, Mock Final Classes
如何在Android Instrumented測試用例中模擬最終類,即在Android Run Time
模擬最終類?
(我正在使用Mockito 2.X
)
我有一個如下的測試用例-
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
// This is my app specific NON - Final class
private ShutdownServicesReqSig rebootSig = ShutdownServicesReqSig.newBuilder(ShutDownType.REBOOT_SYSTEM).setReason("test").build();
private PowerManager mockedPowerManager = null;
private Context mockedContext = null;
@Test
public void testRestart() throws InterruptedException
{
mockedContext = Mockito.mock(Context.class);
mockedPowerManager = Mockito.mock(PowerManager.class); // Here is the problem android.os.PowerManager is a Final class in latest Android SDK
// I need to mock it, only then I can use Mockito.verify() on PowerManager
Mockito.when(mockedContext.getSystemService(Context.POWER_SERVICE)).thenReturn(mockedPowerManager);
assertTrue(executor.requestShutdown(rebootSig));
Thread.sleep(1000);
Mockito.verify(mockedPowerManager).reboot(any(String.class)); // Mocking of PowerManager is essential to be sure of method call on PowerManager, using Mockito.verify
Mockito.reset(mockedPowerManager);
}
}
當我將其作為ART
上的Android Instrumented Test(放置在MyApplication\\app\\src\\androidTest
)運行時,出現以下錯誤-
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class android.os.PowerManager
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
但是,同樣的代碼,當我作為普通的JUnit測試運行時,在JVM
內部(放置在MyApplication\\app\\src\\test
),可以正常工作。
我需要在ART
運行它,因為我想測試一些自定義的Android服務,並且需要模擬諸如PowerManager
最終類,因為只有這樣我才能在PowerManager
上使用Mockito.verify()
來驗證對某些方法的調用PowerManager
。
幫助/指南表示贊賞。
Mockito 2具有“選擇加入”機制,可以模擬最終方法或類,請參見此處 。 通過創建包含一行的文件src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
,可以通過模仿擴展機制啟用它:
mock-maker-inline
(好吧,該文件必須位於類路徑中)。
如果這對您有用,那就完美。 如果沒有,您可能無能為力。
您會發現,檢測歸結為:處理字節碼。 通常,使用一個以上的框架來完成工作是不可行的。
含義:為了實現這種模擬,需要對字節碼進行操作。 出於顯而易見的原因,要使兩個不同的字節碼操作框架很好地共存是一個非常艱巨的挑戰。
長話短說:嘗試這種擴展機制,當它不起作用時,您必須退后一步並問自己:我打算實現的最終目標到底是什么?
最有可能的是,您可能不應該浪費時間嘗試模擬在ART中運行的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.