Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 測試實戰指南:單元測試、UI 測試與常用框架全解析

編輯:Android 資訊

測試驅動開發(TDD)在 RoR 世界早已是標配,是相當可靠的開發思維;但在 Android 這兒卻始終沒有真正普及。今天就把 Android 上的單元測試、儀器測試,以及背後常用的那些庫,一次講清楚。

一、觀念與基本規範

1. 為什麼要測試

  • 為了穩定:讓你能明確回答「這個功能到底有沒有做對」。
  • 為了易於維護:改動程式碼之後,測試替你守住既有的功能。
  • 為了流程:把測試接進工具鏈,讓規範落地。例如在 Phabricator Differential 提交 diff 時附上必須通過的單元測試,等於在開發流程層面就攔住了不穩定的程式碼。

2. 測什麼

  • 一般單元測試:把想覆蓋的異常情境逐一列出來驗證,再加上效能測試。
  • 儀器測試(儀表測試):依需求驗證使用者在真實操作中看到的介面回饋,以及依賴系統架構的元件行為。

3. 幾個容易忽略的細節

  • 可讀性優先。方法名稱要能自我說明,可以採用固定格式,例如 [測試的方法]_[測試的條件]_[預期結果],或參考 RSpec 風格的組織方式。
  • 測試方法裡不要出現 if/else、for、do/while、switch/case。一旦需要條件分支,就該把它拆成多個獨立的測試方法。
  • 只驗證真正該驗證的東西,通常就是輸出:某個操作之後畫面顯示什麼、某個值是多少。
  • 留意耗時,Android Studio 預設就會把執行時間印出來。
  • 不必測試 private 方法,把它當成黑盒的內部零件,測引用它的 public 方法即可;getter、setter 這類瑣碎程式碼也不必測。
  • 每個測試方法之間不能有先後順序,Test A 不該依賴 Test B 的執行結果。

4. 建立測試

把游標停在類別名稱上,按 Alt + Enter,選擇 Create Test 即可。

二、Android Studio 中的兩類測試

Control + Shift + R 是 Android Studio 執行測試的預設快捷鍵。

1. 本地單元測試(Local Test)

直接在開發機的 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,模擬物件
}

JUnit 常用標註

標註說明
@Test宣告該方法為測試方法
@Test(expected = Exception.class)拋出指定型別的例外才算通過
@Test(timeout = 100)執行超過 100 毫秒即判定失敗
@Before每個測試前執行,用來準備環境(初始化物件、讀輸入流等)
@After每個測試後執行,用來清理資料
@BeforeClass全部測試開始前執行一次,適合耗時的初始化(如建立資料庫連線)
@AfterClass全部測試結束後執行一次,適合收尾清理
@Ignore暫時跳過該測試,例如尚未準備好或過於耗時
@FixMethodOrder(MethodSorters.NAME_ASCENDING)讓類別中的測試依方法名字母順序執行
Assume.assumeFalse(condition)條件成立時跳過該方法

2. 儀器測試(Instrumented Test)

必須跑在實機或模擬器上,主要用於 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
}

UI 測試真正該問的三件事

  1. 畫面載入完成後,呈現的資訊是否正確?
  2. 使用者操作之後,介面資訊是否更新正確?
  3. 是否把正確的頁面交給使用者操作?

Espresso

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()));

三、值得加入工具箱的擴充套件

1. AssertJ Android

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");

2. Hamcrest

以既有的通用匹配器快速描述條件,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"));

3. Mockito

建立模擬物件、控制回傳值、驗證方法呼叫,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(); }
}

4. Robolectric

讓儀器測試直接在開發機的 JVM 上跑,不必啟動模擬器。凡是會用到系統元件(例如 Handler、HandlerThread)的測試,Robolectric 都能勝任。

它要解決的正是儀器測試最痛的問題:每次來回裝 app、開模擬器,動輒數分鐘。Robolectric 的做法是為 Android 核心庫提供一組 Shadow Classes,讓這類測試像本地測試一樣快,同時保留系統行為的模擬能力。

5. Robotium

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);
    }
}

這類測試通常還是得跑在模擬器或實機上,特別適合與操作流程、視覺呈現高度相關的驗證。

6. Test Butler

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 找上門,不如現在就把網子張起來。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved