我们可以让Espresso中的当前显示活动写下一些相应的条件代码吗?
在我的应用程序中,我们有一个介绍页面,从下一个应用程序中只显示用户一次,直接将用户带到登录屏幕。我们可以检查用户是在哪个屏幕上登陆的吗?这样我们就可以相应地写下我们的测试用例。
发布于 2016-07-23 00:23:05
你可以把一个唯一的ID放在我们必须检查的布局中。在您描述的示例中,我将在登录布局中添加以下内容:
<RelativeLayout ...
android:id="@+id/loginWrapper"
...然后,在测试中,您只需检查是否显示了此Id:
onView(withId(R.id.loginWrapper)).check(matches(isCompletelyDisplayed()));我不知道有没有更好的方法,但这个方法行得通。
您也可以使用在线找到的waitId方法等待一段时间:
/**
* Perform action of waiting for a specific view id.
* <p/>
* E.g.:
* onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15));
*
* @param viewId
* @param millis
* @return
*/
public static ViewAction waitId(final int viewId, final long millis) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}
@Override
public String getDescription() {
return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
}
@Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + millis;
final Matcher<View> viewMatcher = withId(viewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return;
}
}
uiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
// timeout happens
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
};
}使用此方法,您可以执行以下操作:
onView(isRoot()).perform(waitId(R.id.loginWrapper, 5000));这样,如果登录屏幕需要5秒或更少的时间才会出现,测试也不会失败。
发布于 2016-08-15 07:22:16
在我的Espresso测试类中,我使用ActivityTestRule,因此为了获得当前活动,我使用
mRule.getActivity()下面是我的示例代码:
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SettingsActivityTest {
@Rule
public ActivityTestRule<SettingsActivity> mRule = new ActivityTestRule<>(SettingsActivity.class);
@Test
public void checkIfToolbarIsProperlyDisplayed() throws InterruptedException {
onView(withText(R.string.action_settings)).check(matches(withParent(withId(R.id.toolbar))));
onView(withId(R.id.toolbar)).check(matches(isDisplayed()));
Toolbar toolbar = (Toolbar) mRule.getActivity().findViewById(R.id.toolbar);
assertTrue(toolbar.hasExpandedActionView());
}
}希望能有所帮助
https://stackoverflow.com/questions/38521898
复制相似问题