Android單元測試之四:儀器化測試
儀器化測試
在某些情況下,雖然可以通過模拟的手段來隔離 Android 依賴,但代價很大,這種情況下可以考慮儀器化的單元測試,有助于減少編寫和維護模拟代碼所需的工作量。
儀器化測試是在真機或模拟器上運作的測試,它們可以利用 Android framework APIs 和 supporting APIs 。如果測試用例需要通路儀器(instrumentation)資訊(如應用程式的 Context ),或者需要 Android 架構元件的真正實作(如 Parcelable 或 SharedPreferences 對象),那麼應該建立儀器化單元測試,由于要跑到真機或模拟器上,是以會慢一些。
如何進行儀器化測試
測試使用 SharedPreferences 的工具類,使用 SharedPreferences 需要通路 Context 類以及 SharedPreferences 的具體實作,采用模拟隔離的話代價會比較大,是以采用儀器化測試比較合适。
配置
dependencies {
...
androidTestCompile 'com.android.support:support-annotations:26.1.0'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestCompile 'com.android.support.test:rules:1.0.2'
}
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
測試
被測試類
package com.zm.androidUnitTest;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferenceDao {
private SharedPreferences sp;
public SharedPreferenceDao(SharedPreferences sp) {
this.sp = sp;
}
public SharedPreferenceDao(Context context) {
this(context.getSharedPreferences("config", Context.MODE_PRIVATE));
}
public void put(String key, String value) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.apply();
}
public String get(String key) {
return sp.getString(key, null);
}
}
測試類
package com.zm.androidUnitTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class SharedPreferenceDaoTest {
public static final String TEST_KEY = "name";
public static final String TEST_STRING = "zhangmiao";
SharedPreferenceDao spDao;
@Before
public void setUp() {
spDao = new SharedPreferenceDao(App.getAppContext());
}
@Test
public void sharedPreferenceDaoWriteRead() {
spDao.put(TEST_KEY, TEST_STRING);
Assert.assertEquals(TEST_STRING, spDao.get(TEST_KEY));
}
}
運作方式和本地單元測試一樣,這個過程會向連接配接的裝置安裝 apk。
測試結果

通過測試結果可以清晰看到狀态 passed ,仔細看列印的 log ,可以發現,這個過程向模拟器安裝了兩個 apk 檔案,分别是 AndroidUnitTest-debug.apk 和 AndroidUnitTest-debug-androidTest.apk , instrumented 測試相關的邏輯在 AndroidUnitTest-debug-androidTest.apk 中。
參考文章