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

打造快速可靠的 Android UI 測試:Espresso + Mockito + Dagger 2

編輯:Android 資訊

一個三分鐘跑完 250 個測試的故事

Iván Carballo 與他的團隊用 Espresso、Mockito 與 Dagger 2 寫出了 250 個 UI 測試,而且只需要三分鐘就能全部跑完。這篇整理了他們的做法,很適合正在起步、或想改善測試效能的開發者參考。

幾年前我第一次在 Android 專案裡導入 UI 自動化測試,用的是 Robotium。當時我堅信測試環境越真實越好:測試應該像超人一樣能瞬間點擊任何位置而且絕不報錯。至於 mocking,我覺得很糟糕——測試時改變 App 行為,不就是自欺欺人嗎?

幾個月後,我們有了大約 100 個測試,跑一輪要 40 分鐘。它們極不穩定,即使功能完全正常,也常常有一半機率失敗。我們投入大量時間維護,卻幾乎沒靠它們找到過真正的問題。

但正如 John Dewey 所說,失敗是具有啟發意義的。智者總能從失敗和成功中學到同樣多的東西。

我們確實學到了教訓:在測試中依賴真實 API 是個錯誤的決定。一旦失去對回傳資料的控制,就無法為測試預先安排情境。網路故障、外部服務出錯,都會讓測試跟著掛掉。你的 Wi-Fi 不穩,測試不該跟著不穩。如果測試還在依賴外部 API,那它其實是整合測試,拿不到我們想要的結果。

Mock:真正的解法

Mock 就是用一個模擬物件替換真實物件。它主要用在單元測試,但在 UI 測試裡同樣非常有效。模擬 Java 物件的方式有很多種,Mockito 是其中簡單又實用的一種。下面的例子建立了一個 UsersApi 的 mock,並把其中一個方法 stub 掉,讓它固定回傳三個使用者名稱:

class UsersApi { String[] getUserNames() { } } // Create the mock version of a UsersApi class UsersApi mockApi = Mockito.mock(UsersApi.class); // Stub the getUserNames() method when(mockApi.getUserNames()) .thenReturn(new String[]{"User1", "User2", "User3"}); // The call below will always return an array containing the // three users named above mockApi.getUserNames();

真正的難點不在建立 mock,而在「怎麼讓 App 在測試時用 mock、正式執行時用真實物件」。如果你的程式碼不利於測試,替換過程會變得極度痛苦,甚至根本做不到。另外要注意,想模擬的邏輯必須獨立在自己的類別裡——如果你直接在 Activity 中用 HttpURLConnection 呼叫 REST API(希望你不會這樣做),那幾乎無法模擬。

先想清楚架構再寫測試。糟糕的架構會讓測試與 mock 難寫又不穩定。

一個好測試的架構

有利於測試的架構有很多種寫法。這裡採用 ribot 專案中的架構作為範例,但概念可以套用到任何結構上。我們的架構基於 MVP,並決定在 UI 測試中把整個 Model 層 mock 掉,這樣就能完全掌控資料,寫出更有價值也更穩定的測試。

MVP 架構中,DataManager 是 Model 層唯一暴露給 Presenter 的資料入口,所以要攔截資料,只需把它換成 mock 的 DataManager 即可。

用 Dagger 2 注入 mock DataManager

確認要模擬什麼之後,下一步是想辦法在測試中完成替換。我們用 Dagger 2(Android 的依賴注入框架)解決。專案裡至少有一個 Module 與一個 Component,通常命名為 ApplicationModule 與 ApplicationComponent。下面是簡化後只提供 DataManager 的版本(你也可以直接在 DataManager 建構子上標 @Inject,這裡用最直觀的寫法):

@Module public class ApplicationModule { @Provides @Singleton public DataManager provideDataManager() { return mDataManager; } } @Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent { DataManager dataManager(); }

ApplicationComponent 在 Application 類別中初始化,同時多開一個 setter,方便測試時替換:

public class MyApplication extends Application { ApplicationComponent mApplicationComponent; public ApplicationComponent getComponent() { if (mApplicationComponent == null) { mApplicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build(); } return mApplicationComponent; } // Needed to replace the component with a test specific one public void setComponent(ApplicationComponent applicationComponent) { mApplicationComponent = applicationComponent; } }

接著建立測試專用的 Module 與 Component:

@Module public class TestApplicationModule { // We provide a mock version of the DataManager using Mockito @Provides @Singleton public DataManager provideDataManager() { return Mockito.mock(DataManager.class); } } @Singleton @Component(modules = TestApplicationModule.class) public interface TestComponent extends ApplicationComponent { // Empty because extends ApplicationComponent }

TestApplicationModule 用 Mockito 提供 mock 的 DataManager,而 TestComponent 繼承 ApplicationComponent 並換成這個 Module。只要把 Application 中的 Component 換成 TestComponent,App 拿到的就是 mock 物件。

寫一個 JUnit Rule 負責切換 Component

為了確保每個測試跑之前 TestComponent 都已就位,我們實作一個 JUnit 4 的 TestRule:

public class TestComponentRule implements TestRule { private final TestComponent mTestComponent; private final Context mContext; public TestComponentRule(Context context) { mContext = context; MyApplication application = (MyApplication) context.getApplicationContext(); mTestComponent = DaggerTestComponent.builder() .applicationTestModule(new ApplicationTestModule(application)) .build(); } public DataManager getMockDataManager() { return mTestComponent.dataManager(); } @Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { MyApplication application = (MyApplication) context.getApplicationContext(); // Set the TestComponent before the test runs application.setComponent(mTestComponent); base.evaluate(); // Clears the component once the tets finishes so it would use the default one. application.setComponent(null); } }; } }

TestComponentRule 會建立 TestComponent 實例,並改寫 apply() 回傳新的 Statement,該 Statement 依序做三件事:

1 把 TestComponent 設給 Application;

2 呼叫原 Statement 的 evaluate(),也就是實際的測試內容;

3 跑完後把 Application 的 component 設回 null,恢復初始狀態。這一步很關鍵,可以避免測試之間互相污染。

有了 getMockDataManager(),我們就能取得 mock 物件並 stub 它的方法。這裡有個容易忽略的前提:provideDataManager 必須標上 @Singleton,否則 getMockDataManager 拿到的會是另一個實例,stub 自然不生效。

動手寫測試

配置就緒後,用 Espresso 來寫 UI 測試。它並非完美,但足夠快也夠可靠。假設我們有一個很簡單的 App:從 REST API 載入使用者名稱並顯示在 RecyclerView 上,對應的 Activity 叫 UsernamesActivity。DataManager 大致如下:

public DataManager { // Loads usernames from a REST API using a Retrofit public Single<List<String>> loadUsernames() { return mUsersService.getUsernames(); } }

loadUsernames() 透過 Retrofit 與 RxJava 取回資料,回傳一個 Single。為了清楚起見,這裡省略了 presenter 的部分。

我們至少要驗證三種情境:

1 API 回傳有效列表時,資料要顯示在畫面上;

2 API 回傳空列表時,畫面顯示「空列表」提示;

3 API 請求失敗時,畫面顯示錯誤訊息。

@Test public void usernamesDisplay() { // Stub the DataManager with a list of three usernames List<String> expectedUsernames = Arrays.asList("Joe", "Jemma", "Matt"); when(component.getMockDataManager().loadUsernames()) .thenReturn(Single.just(expectedUsernames)); // Start the Activity main.launchActivity(null); // Check that the three usernames are displayed for (Sting username:expectedUsernames) { onView(withText(username)) .check(matches(isDisplayed())); } } @Test public void emptyMessageDisplays() { // Stub an empty list when(component.getMockDataManager().loadUsernames()) .thenReturn(Single.just(Collections.emptyList())); // Start the Activity main.launchActivity(null); // Check the empty list message displays onView(withText("Empty list")) .check(matches(isDisplayed())); } @Test public void errorMessageDisplays() { // Stub with a Single that emits and error when(component.getMockDataManager().loadUsernames()) .thenReturn(Single.error(new RuntimeException())); // Start the Activity main.launchActivity(null); // Check the error message displays onView(withText("Error loading usernames")) .check(matches(isDisplayed())); } }

這裡同時用到 TestComponentRule 與官方提供的 ActivityTestRule,後者負責從測試中啟動 Activity。要特別注意順序:用 RuleChain 確保 TestComponentRule 一定先於 ActivityTestRule 執行,這樣 Component 才會在任何 Activity 起來之前設定完成。

三個測試其實遵循同一個骨架:

1 用 when(xxx).thenReturn(yyy) 設定前置條件,也就是 stub loadUsernames();

2 用 main.launchActivity(null) 啟動 Activity;

3 用 check(matches(isDisplayed())) 驗證畫面符合前置條件所期待的結果。

這套做法的威力在於:你對整個 App 的初始狀態擁有絕對控制權,能測試各種情境。若不使用 mock,這三個用例幾乎不可能寫出來,因為真實 API 永遠只回傳同一份資料。

想看完整可運行的範例,可以參考 GitHub 上的 ribot Android boilerplate 或 ribot app。

這套方案的代價

它並不完美。第一,每個測試前都要寫 stub 顯得繁瑣,複雜界面可能需要在單個測試裡準備五到十個 stub。把共同的 stub 抽到 setup() 有幫助,但不同測試往往需要的 stub 也不同。第二,UI 測試與實作存在耦合,一旦重構 DataManager,所有 stub 都得跟著改。

即便如此,我們已在 ribot 的幾個專案中採用這種方式,成效不錯:最近一個 Android 專案裡有 250 個 UI 測試能在三分鐘內跑完,另外還有 380 個 Model 層與 Presenter 層的單元測試。

希望這套思路能幫你重新看待 UI 測試,也寫出更好維護的測試程式碼。

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