最近需要寫一些 Android 的自動化測試用例. 就學習了一下 Espresso 框架的用法.
參考文章
環境配置
環境配置可以參考: Getting Started with Testing
其實只需要安裝步驟建好文件夾, 然后在 gradle 文件中添加依賴即可.
這一步當中, 文檔特地提到要先關閉動畫, 不然可能會導致問題. 雖然不知道會導致什么問題, 但是血的教訓告訴我文檔讓你做的一定要做. 打開開發者選項, 關閉以下三個選項:
- 窗口動畫縮放(Window animation scale)
- 過渡動畫縮放(Transition animation scale)
- 動畫程序時長縮放(Animator duration scale)
Espresso 的核心類
如果去看一些 Espresso 的例子. 你會看到類似下面的代碼:
onView(withId(R.id.test)).perform(click()).check(matchers(withText("xxx")))
如果使用過 Hamcrest 應該會感到很親切.
代碼大量使用 static import 來提高可讀性. 如果去掉 static import 的部分, 就變成這樣:
Espresso.onView(ViewMatchers.withId(R.id.test))
.perform(ViewActions.click())
.check(ViewAssertion.matches(ViewMatchers.withText("xxx")))
其實包含了 Espresso 中重要的四個類1:
- Espresso:
跟 View 交互的入口(onView 或者 onData). 其實 Espresso 并不一定需要跟一個 View 綁定, 比如 pressBack - ViewMachers
包含了很多實現 Matcher<? super View> 的對象. 通過 onView 和 ViewMathcers 可以在 View Hierarchy 中定位 View. - ViewActions
顧名思義, 就是一些可以對 view 做的動作, 比如click, typeText. 使用方式就是作為參數傳遞給ViewInteraction.preform()
- ViewAssertions
一系列ViewAssertion
的集合, 可以作用參數傳遞給ViewInteraction.check()
. 通常你需要使用 matches assertion. 通過 ViewMatcher 來判斷 View 的狀態.