編輯:Android 資訊
測試驅動開發(TDD)在 RoR 世界早已是標配,是相當可靠的開發思維;但在 Android 這兒卻始終沒有真正普及。今天就把 Android 上的單元測試、儀器測試,以及背後常用的那些庫,一次講清楚。
[測試的方法]_[測試的條件]_[預期結果],或參考 RSpec 風格的組織方式。把游標停在類別名稱上,按 Alt + Enter,選擇 Create Test 即可。
Control + Shift + R是 Android Studio 執行測試的預設快捷鍵。
直接在開發機的 JVM 上執行。沒有相依、或只相依少數純 Java 庫時,優先選它。
執行指令:./gradlew check
程式碼位置:src/test/java。若依 flavors 或 build type 區分,加上對應後綴即可,例如名為 myFlavor 的測試放在 src/testMyFlavor/java。
Google 官方建議的相依:
dependencies {
testCompile 'junit:junit:4.12' // JUnit 4,單元測試首選
testCompile 'org.mockito:mockito-core:1.10.19' // Mockito,模擬物件
}
| 標註 | 說明 |
|---|---|
@Test | 宣告該方法為測試方法 |
@Test(expected = Exception.class) | 拋出指定型別的例外才算通過 |
@Test(timeout = 100) | 執行超過 100 毫秒即判定失敗 |
@Before | 每個測試前執行,用來準備環境(初始化物件、讀輸入流等) |
@After | 每個測試後執行,用來清理資料 |
@BeforeClass | 全部測試開始前執行一次,適合耗時的初始化(如建立資料庫連線) |
@AfterClass | 全部測試結束後執行一次,適合收尾清理 |
@Ignore | 暫時跳過該測試,例如尚未準備好或過於耗時 |
@FixMethodOrder(MethodSorters.NAME_ASCENDING) | 讓類別中的測試依方法名字母順序執行 |
Assume.assumeFalse(condition) | 條件成立時跳過該方法 |
必須跑在實機或模擬器上,主要用於 Android SDK 相依的單元測試、UI 測試,以及 Service、Content Provider 等元件的整合測試。
執行指令:./gradlew connectedAndroidTest
程式碼位置:src/androidTest/java
dependencies {
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3' // Hamcrest
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1' // Espresso
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1' // UI Automator
}
Google 官方提供的 UI 交互測試框架,語法貼近自然語言:
// 對 R.id.my_view 觸發點擊,並檢查它是否顯示中
onView(withId(R.id.my_view)).perform(click()).check(matches(isDisplayed()));
// 對文字以 "ABC" 開頭的 View,檢查是否為未啟用狀態
onView(withText(startsWith("ABC"))).check(matches(not(isEnabled())));
pressBack(); // 按返回鍵
// 輸入文字後收起軟鍵盤
onView(withId(R.id.inputField)).perform(typeText("NewText"), closeSoftKeyboard());
// 清空輸入框
onView(withId(R.id.inputField)).perform(clearText());
要測試需要 Intent 參數的 Activity,用 ActivityTestRule 控制啟動時機:
@RunWith(AndroidJUnit4.class)
public class SecondActivityTest {
@Rule public ActivityTestRule<SecondActivity> rule =
new ActivityTestRule(SecondActivity.class, true, false); // 第三個參數為 false 代表不自動啟動
@Test public void demonstrateIntentPrep() {
Intent intent = new Intent();
intent.putExtra("EXTRA", "Test");
rule.launchActivity(intent);
onView(withId(R.id.display)).check(matches(withText("Test")));
}
}
建議先把裝置「設定 → 開發者選項」中的三項動畫關掉(Window animation scale、Transition animation scale、Animator duration scale),否則 Espresso 在判斷非同步任務時容易誤判。
針對 IntentService 這類場景,做法是自實作 IdlingResource:空閒時才放行檢測,忙碌期間自動阻塞。
public class IntentServiceIdlingResource implements IdlingResource {
ResourceCallback resourceCallback;
private Context context;
@Override public boolean isIdleNow() {
boolean idle = !isIntentServiceRunning();
if (idle && resourceCallback != null) resourceCallback.onTransitionToIdle();
return idle;
}
private boolean isIntentServiceRunning() {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo info : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyIntentService.class.getName().equals(info.service.getClassName())) return true;
}
return false;
}
}
// 使用方式
@Before public void before() {
idlingResource = new IntentServiceIdlingResource(InstrumentationRegistry.getTargetContext());
Espresso.registerIdlingResources(idlingResource);
}
@After public void after() { Espresso.unregisterIdlingResources(idlingResource); }
public static Matcher<View> withItemHint(final Matcher<String> matcherText) {
return new BoundedMatcher<View, EditText>(EditText.class) {
@Override public void describeTo(Description description) {
description.appendText("with item hint: " + matcherText);
}
@Override protected boolean matchesSafely(EditText editTextField) {
return matcherText.matches(editTextField.getHint().toString());
}
};
}
// 使用:onView(withItemHint("test")).check(matches(isDisplayed()));
square/assertj-android,大幅改善斷言的可讀性:
assertThat(view).isGone();
assertThat(test.getName()).isEqualTo("Frodo");
assertThat(test).isNotEqualTo(test1).isIn(testList);
assertThat(test.getName()).startsWith("Fro").endsWith("do").isEqualToIgnoringCase("frodo");
assertThat(list).hasSize(2).contains(test, test1).doesNotContain(test2);
assertThat(testList).extracting("name").contains("Frodo", "Sauron").doesNotContain("Jacks");
以既有的通用匹配器快速描述條件,org.hamcrest:hamcrest-junit:(version):
assertThat(a, equalTo(b)); assertThat(a, is(equalTo(b))); assertThat(actual, is(not(equalTo(b)))); assertThat(list, hasSize(3)); assertThat(list, contains(5, 2, 4)); // 順序也要一致 assertThat(list, containsInAnyOrder(2, 4, 5)); // 順序不拘 assertThat(list, everyItem(greaterThan(1))); assertThat(object1, samePropertyValuesAs(object2)); assertThat(ints, arrayContaining(7, 5, 12, 16));
主要匹配器:allOf(全部滿足)、anyOf(任一滿足)、not、equalTo、instanceOf / isCompatibleType、notNullValue / nullValue、sameInstance、hasEntry / hasKey / hasValue、hasItem / hasItems、hasItemInArray、closeTo、greaterThan 系列、equalToIgnoringCase、equalToIgnoringWhiteSpace、containsString / startsWith / endsWith / isEmptyString。
自訂匹配器只要繼承 TypeSafeMatcher:
public class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex;
@Override public boolean matchesSafely(final String string) { return string.matches(regex); }
public static RegexMatcher matchesRegex(final String regex) { return new RegexMatcher(regex); }
}
// 使用:assertThat("aaabbbaaa", RegexMatcher.matchesRegex("a*b*a"));
建立模擬物件、控制回傳值、驗證方法呼叫,org.mockito:mockito-all:(version):
MyClass test = mock(MyClass.class);
when(test.getUniqueId()).thenReturn(43);
when(test.compareTo(anyInt())).thenReturn(43);
when(test.compareTo(isA(Target.class))).thenReturn(43);
doThrow(new IOException()).when(test).close();
doNothing().when(test).execute();
verify(test, times(2)).getUniqueId(); // 恰好兩次
verify(test, never()).getUniqueId(); // 從未呼叫
verify(test, atLeast(2)).getUniqueId(); // 至少兩次
verify(test, atMost(3)).getUniqueId(); // 最多三次
verify(test).query("test string"); // 以指定參數呼叫過
List list = new LinkedList();
List spy = spy(list);
doReturn("foo").when(spy).get(0);
需要對傳入參數做快照時使用 ArgumentCaptor。特別注意:若方法簽章是可變參數(String... params),要用 ArgumentCaptor<String> 而非 ArgumentCaptor<String[]>,並以 getAllValues() 取出全部傳入值。
要 mock 靜態方法,可以借助 PowerMock(powermock-api-mockito 與 powermock-module-junit4):
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass1.class, StaticClass2.class})
public class MyTest {
@Test public void testSomething() {
mockStatic(StaticClass1.class);
when(StaticClass1.getStaticMethod()).andReturn("anything");
verifyStatic(time(1));
StaticClass1.getStaticMethod();
}
}
另一條路是把靜態呼叫包成非靜態方法,再用 Mockito 處理:
class FooWraper {
void someMethod() { Foo.someStaticMethod(); }
}
讓儀器測試直接在開發機的 JVM 上跑,不必啟動模擬器。凡是會用到系統元件(例如 Handler、HandlerThread)的測試,Robolectric 都能勝任。
它要解決的正是儀器測試最痛的問題:每次來回裝 app、開模擬器,動輒數分鐘。Robolectric 的做法是為 Android 核心庫提供一組 Shadow Classes,讓這類測試像本地測試一樣快,同時保留系統行為的模擬能力。
RobotiumTech/robotium,以模擬使用者操作的事件流進行整合測試:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class MyActivityTest {
@Test public void doSomethingTests() {
WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
activity.findViewById(R.id.login).performClick();
Intent expectedIntent = new Intent(activity, LoginActivity.class);
assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent);
}
}
這類測試通常還是得跑在模擬器或實機上,特別適合與操作流程、視覺呈現高度相關的驗證。
linkedin/test-butler,用來排除環境因素造成的假性失敗。
做 UI 測試時,你一定遇過這類惱人狀況:模擬器系統崩潰、ANR、Wi-Fi 莫名中斷、CPU 被搶走、螢幕被鎖上——測試其實沒錯,卻紅了。Test Butler 就是為了吸收這些環境雜訊而生,它曾獲 Google 官方推薦並經其工程師 review。
來自 Jake Wharton 的 Instrumentation Testing Robots 概念。假設要驗證「發送 $42 到 foo@bar.com 之後是否成功」。
傳統寫法會把每個操作步驟細節都攤在測試裡:


Robot 的思路是把「怎麼做」封裝起來:

於是測試本身只剩下「要驗證什麼」:

最終效果是讓測試邏輯與 View 或 Presenter 解耦,改而與資料及行為對齊:

測試寫得好不好,往往決定一個專案半年後還能不能安心改。與其等 bug 找上門,不如現在就把網子張起來。
Android Hook 技術入門:Xposed 與 Frida 實戰解析
前言 Xposed 框架 Xposed 的主頁是:https://repo.xposed.info/module/de.robv.android.xposed.insta
視頻縮略圖不卡頓:異步加載與 LruCache 緩存實作
這次的開發項目裡有個視頻列表,需要展示視頻縮略圖。在很多人看來,生成視頻縮略圖無非兩行代碼的事——確實,搜一下每篇帖子都會告訴你怎麼做,本文用的也是同一套 API。真正的
Android 性能優化中的電量管理實務
在行動裝置上,電量是非常寶貴的資源。應用若經常喚醒裝置、頻繁網路請求或長時間持有 wakelock,都可能顯著增加耗電。Google 在 Android 性能優化課程中,
Android 實現帶動畫的下拉刷新 RecyclerView
RecyclerView 是 Android 中常見的列表元件。若要在列表中加入下拉刷新、上拉載入與動畫效果,可以考慮使用開源的 AnimRefreshRecyclerV