Espresso自动化测试,创建项目时已导入相对应的包。
-
打开sdk(
D:\java\androidstudio\sdk\tools
)中的tools文件夹下的uiautomatorviewer.bat,点击下图中红色框中的内容捕获一帧画面。
-
Run->点击Record Espresso Test,提示运行安装程序
-
点击确定后出现如下界面
-
点击上图中的Add Assertion按钮,配合uiautomatorviewer点击控件增加断言
-
选择Save Assertion来保存断言并退出此窗口
-
点击Complete Recording按钮,完成录制。此时需要填写一个测试的类名,然后点击Save。
-
保存之后,就在androidTest目录的包下生成一个测试类.
测试类代码如下:
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void mainActivityTest() {
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.btn_open), withText("open"),
withParent(allOf(withId(R.id.activity_main),
withParent(withId(android.R.id.content)))),
isDisplayed()));
appCompatButton.perform(click());
ViewInteraction textView = onView(
allOf(withText("登录成功"),
childAtPosition(
allOf(withId(R.id.activity_login),
childAtPosition(
withId(android.R.id.content),
0)),
0),
isDisplayed()));
textView.check(matches(withText("登录成功")));
}
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));
}
};
}
}
-
这时,在刚刚生成的测试类右键,选择Run 'MainActivityTest' 点击运行,此时代码执行的过程即是刚刚操作的步骤。