LoginSignup
23
21

More than 5 years have passed since last update.

Espressoの導入 & Espressoでハマったこと

Last updated at Posted at 2015-07-16

※まだ使い始めたばかりなので徐々に追記していきます。

Espressoとは

JUnitを使ったAndroidのUIテストを実装できるライブラリです。
Android Support Library の一部なので、Android SDKから Android Support Repository をインストールすることで利用することができます。

Espressoの導入

build.gradle にandroidTestCompile指定でテストを利用するための依存関係を追加してください。これだけです!

build.gradle
dependencies {
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

Espresssoのサンプル

ポイント

  • クラス宣言時に @RunWith(AndroidJUnit4.class) アノテーションを付与する
  • @Rule アノテーションを付与した ActivityTestRule でテストを開始する
  • テストメソッドには @Test アノテーションを付与する
MainActivityTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    @Test
    public void testSearch() {
        // 検索テスト
        Espresso.onView(ViewMatchers.withId(R.id.edittext_key_word)).perform(ViewActions.typeText("hoge"));
        Espresso.onView(ViewMatchers.withId(R.id.button_search)).perform(ViewActions.click());
    }

}

Espressoでハマったこと

マルチバイト文字がEditText等に入力できない!

ViewActions.typeText を使ってマルチバイト文字を入力しようとすると、テストに失敗します。マルチバイト文字をEditText等に入力する場合は ViewActions.replaceText を使うことで入力できるようになります。

Test.java
// OK
onView(withId(R.id.edittext)).perform(replaceText("入力できる"));

// NG
onView(ViewMatchers.withId(R.id.edittext)).perform(typeText("エラーになる"));
Error
java.lang.RuntimeException: Failed to get key events for string エラーになる (i.e. current IME does not understand how to translate the string into key events). As a workaround, you can use replaceText action to set the text directly in the EditText field.

Viewを操作できない!

実際に操作している状態と同じで、画面に表示されていないViewは操作できません。そのため、scrollTo で操作したいViewまでスクロールする必要があります。

Test.java
//scrollTo() でスクロールしてからclick
onView(withId(R.id.button)).perform(scrollTo(), click()); 
23
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
21