使用 Android Test Orchestrator 讓 Espresso Test 變得更穩定

林杰毅
AppDev Ooops
Published in
3 min readAug 2, 2019

Android Test Orchestrator 是一個工具,可以讓你的每個測試 (有上 @Test 的 method) 被跑在 AndroidJUnitRunner 的各自獨立 instance 上。
這個工具幫助我們解決了什麼問題呢?
1. 當測試 crash 發生時,不會中斷所有的測試
2. 在每個測試後會自動清除 CPU 跟 Memory,並將 App 的一些狀態恢復到初始狀態。例如:以 KKBOX 為例,上個測試會讓 KKBOX 處於正在播放音樂的狀態,新的測試開始跑時會是無播放音樂的狀態。

怎麼使用它呢?

首先你必須加入以下設定到你的 build.gradle 裡

如果需要每次測試前都完全地清空所有資料 ,那就需要在 defaultConfig 中再加上以下設定

testInstrumentationRunnerArguments clearPackageData: ‘true’

不過加上這行設定,會讓你每次跑測試前都需要再重新授與 App 權限,所以要不要加上這行,就看個人的需求囉。

跑起來!!

Orchestrator 如何 Work

以下是官方文件所述:

The Orchestrator service APK is stored in a process that’s separate from the test APK and the APK of the app under test, as shown in Figure 1:

Orchestrator 架構圖

Android Test Orchestrator collects JUnit tests at the beginning of your test suite run, but it then executes each test separately, in its own instance of Instrumentation.

用 Android Studio 執行測試

如果你的測試裝置是第一次使用 Orchestrator ,你會發現在跑測試時,總共會安裝 4 個 apk ,如下方所示

用指令執行測試

必須先確保測試裝置有安裝以下兩個 apk
1. orchestrator-1.x.x.apk
2. test-services-1.x.x.apk

總結

這篇主要也只是簡單的介紹一下並講解如何安裝 Android Test Orchestrator 這個工具,使用這個工具可以幫助我們
1. 降低 flaky
2. 減少些許的 Setup & Teardown

另外如果想要更深入研究的話,可以參考下面這篇

--

--