Espresso-testing-test-recorder

提供:Dev Guides
移動先:案内検索

エスプレッソテストフレームワーク-テストレコーダー

テストケースを書くのは退屈な仕事です。 エスプレッソは非常に簡単で柔軟なAPIを提供しますが、テストケースの作成は怠zyで時間のかかるタスクです。 これを克服するために、Androidスタジオはエスプレッソテストケースを記録および生成する機能を提供します。 _Record Espresso Test_は、_Run_メニューで使用できます。

以下の手順に従って、_HelloWorldApp_に簡単なテストケースを記録しましょう。

  • Androidスタジオを開き、_HelloWorldApp_アプリケーションを開きます。
  • RunRecord Espresso testをクリックして、_MainActivity_を選択します。
  • _Recorder_スクリーンショットは次のとおりです。

レコーダーのスクリーンショット

  • [アサーションの追加]をクリックします。 以下に示すように、アプリケーション画面が開きます。

表示画面

  • [Hello World!]をクリックします。 _Recorder_画面から_Select text view_へは、次のとおりです。

レコーダー画面

  • もう一度[アサーションの保存]をクリックします。これにより、アサーションが保存され、次のように表示されます。

アサーション

  • [OK]をクリックします。 新しいウィンドウが開き、テストケースの名前が尋ねられます。 デフォルト名は_MainActivityTest_です
  • 必要に応じて、テストケース名を変更します。
  • もう一度、[OK]をクリックします。 これにより、記録されたテストケースを含む_MainActivityTest_ファイルが生成されます。 完全なコーディングは次のとおりです。
package com.finddevguides.espressosamples.helloworldapp;

import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import androidx.test.espresso.ViewInteraction;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
   @Rule
   public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
   @Test
   public void mainActivityTest() {
      ViewInteraction textView = onView(
         allOf(withId(R.id.textView_hello), withText("Hello World!"),
         childAtPosition(childAtPosition(withId(android.R.id.content),
         0),0),isDisplayed()));
      textView.check(matches(withText("Hello World!")));
   }
   private static Matcher<View> childAtPosition(
      final Matcher<View> parentMatcher, final int position) {
      return new TypeSafeMatcher<View>() {
         @Override
         public void describeTo(Description description) {
            description.appendText("Child at position " + position + " in parent ");
            parentMatcher.describeTo(description);
         }
         @Override
         public boolean matchesSafely(View view) {
            ViewParent parent = view.getParent();
            return parent instanceof ViewGroup &&
               parentMatcher.matches(parent)&& view.equals(((ViewGroup)
               parent).getChildAt(position));
         }
      };
   }
}
  • 最後に、コンテキストメニューを使用してテストを実行し、テストケースが実行されるかどうかを確認します。