Espresso Testing 框架 - 测试记录器



编写测试用例是一项繁琐的工作。即使 Espresso 提供了非常简单灵活的 API,但编写测试用例可能是一项懒惰且耗时的任务。为了克服这个问题,Android Studio 提供了一项用于记录和生成 Espresso 测试用例的功能。Record Espresso TestRun 菜单下可用。

让我们按照以下步骤在HelloWorldApp 中记录一个简单的测试用例。

  • 打开 Android Studio,然后打开HelloWorldApp 应用程序。

  • 单击RunRecord Espresso 测试并选择MainActivity

  • Recorder 屏幕截图如下所示,

Recorder Screenshot
  • 单击Add Assertion。它将打开应用程序屏幕,如下所示,

Screen As Shown
  • 单击Hello World!。选择文本视图的Recorder 屏幕如下所示,

Recorder Screen
  • 再次单击Save Assertion,这将保存断言并显示如下所示,

Assertion
  • 单击OK。它将打开一个新窗口并询问测试用例的名称。默认名称为MainActivityTest

  • 如果需要,更改测试用例名称。

  • 再次单击OK。这将生成一个文件MainActivityTest,其中包含我们记录的测试用例。完整的编码如下所示,

package com.tutorialspoint.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));
         }
      };
   }
}
  • 最后,使用上下文菜单运行测试并检查测试用例是否运行。

广告