Espresso 簡單入門

weixin_34402408發表於2016-09-04

最近需要寫一些 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 的狀態.