もやもやエンジニア

IT系のネタで思ったことや技術系のネタを備忘録的に綴っていきます。フロント率高め。

AndroidでEspresso + Spoonでキャプチャを撮りつつUIテストを走らせる

Android実機上でのテストにはEspressoというテスティングフレームワークを使いますが、Spoonというライブラリと組み合わせることでUIテスト実行時のキャプチャを残すことができます。導入してみたのでメモになります。

導入

  • Espressoは導入済の状態からSpoonを入れます。この記事を書いている時点でのバージョンは以下の通りです。

    • Espresso : 2.2.2
    • Spoon : 1.6.4
  • プロジェクトのbuild.gradleにプラグインを追加。

buildscript {
    dependencies {
        ...
        classpath 'com.stanfy.spoon:spoon-gradle-plugin:1.2.2'
    }
}
  • アプリケーションのbuild.gradleにライブラリを追加。プラグインも有効にしておく。
apply plugin: 'spoon'

spoon {
    // for debug output
    debug = true

    // To execute the tests device by device */
    sequential = true

    // To grant permissions to Android M >= devices */
    grantAllPermissions = true
}

dependencies {
    ...
    androidTestCompile group: 'com.squareup.spoon', name: 'spoon-client', version: '1.6.4'
}
  • これで準備はできました。

キャプチャを撮る

  • テストメソッド内でSpoon.screenshotを呼ぶことで実行時のキャプチャを残せます
    @Test
    fun testInitializedView() {

        // これでキャプチャを残せる
        Spoon.screenshot(activityRule.activity, "initial_state")

        onView(withId(R.id.fragment_initialize_edit_hatena_id))
                .perform(closeSoftKeyboard(), scrollTo())
                .check(matches(isDisplayed()))

        onView(withId(R.id.fragment_initialize_button_set_hatena_id))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .check(matches(not(isEnabled())))

        onView(withId(R.id.fab))
                .check(matches(not(isDisplayed())))
    }
  • 実行するときはGradleのタスクとして実行します。他のテストタスクと同じようにspoonDebugのようにフレーバーをつけることも可能です。
./gradlew spoon 

実行結果

  • 実行結果は通常のEspressoの実行結果とは異なり app/build/spoon の下に格納されます。実行されると以下のように表示されます。
  • 画像にはメソッド呼び出し時のタグが振られているのでどの時点のキャプチャかわかるようになっています。

f:id:Rei19:20160910212252p:plain:w300

コード

  • こちらが個人のアプリに導入した時のプルリクになります。参考までに。

add Spoon plugin by rei-m · Pull Request #219 · rei-m/HBFav_material · GitHub