Android新提供的測試框架支援庫學習 && Testing Support Library
本文半翻譯與google官方文件,在學習之後,需要了解的是android提供的測試庫工具,以及瞭解它們的作用,以前都是用junit3寫robotium的,現在與時俱進吧。
android提供多重測試用的支援庫,比如說junit4的支援以及ui測試。這一篇文件告訴我們android測試支援庫提供了什麼樣的工具以及怎麼使用它們。
android測試支援庫包含了下面幾個自動化工具:
AndroidJunitRunner 為android提供junit4支援
Espresso 測試框架
Ui Automator 測試框架
AndroidJunitRunner:
這個類支援Espresso和Ui Automator測試框架,執行並監控你的測試結果,這是用來替代只能執行junit3的instrumentationTestunner的。(這個可以匯出報告,非常方便,junit4確實很方便),有如下優點:
1.Junit 支援
支援junit3和junit4,但是不推薦混合編寫,如果你用junit4的格式,在類前面宣告
@RunWith(AndroidJunit4.class)。
2.使用instrumentation特性
你可以使用 InstrumentationRegistry這個類獲取你的測試相關資訊,這個類就是包含Instrumentation物件的和Context物件,這些物件對你寫測試用例是很有用的。
3.測試過濾器
使用annotations多重標籤測試,這個特性會減少你的程式碼標記,除了junit4特有的標記,還可以使用android新增的特性。
比如說:
@RequiresDevice
只能執行在真機中
@sdkSupress
@SDKSupress(minSdkVersion=18).最低執行版本
@smallTest @MediumTest @LargeTest
4.測試分享
就是一個用例支援跑多臺機器
測試依賴框架配置
測試支援庫是可以通過Android SDK Manager下載的:
1. Android Support Repository item.
2. Click the Install packages… button.
下載完後測試依賴庫都是在android.support.test包下面。所以要使用這些庫,需要在gradle中新增
dependencies {
androidTestCompile 'com.android.support.test:runner:0.4'
// Set this dependency to use JUnit 4 rules
androidTestCompile 'com.android.support.test:rules:0.4'
// Set this dependency to build and run Espresso tests
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
// Set this dependency to build and run UI Automator tests
androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'
}
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
Espresso:
谷歌其實說了Espresso是做白盒測試適用的。
同步UI執行緒
之前的測試框架都是需要等view出現才能夠執行和斷言,解決辦法是延遲xx秒。但是Espresso解決了Instrumentation和UI執行緒之間的同步問題,可以讓你在執行之前不用sleep了。
UI Automator:
谷歌推薦用來做黑盒自動化,具體用法就不說了。
總結:
本篇文件介紹了android.support.test包中,也就是android提供的測試支援庫,其中androidjunitrunner是谷歌專門為android開發的用來替代InstrumentationTestRunner的類,允許你在android測試中用junit4,並且增加了獨有的annotation標記,android的測試用例都支援androidjunit。後面介紹了兩個自動化框架,espresso和uiautomator,其中espresso解決了UI執行緒同步的問題。官方建議是前者更適合做白盒測試後者更適合做黑盒自動化。