5

I've just started using Espresso, before that I have tried Robotium. I need to test LoginActivity. The logic is:

  1. User enters correct credentials;
  2. User sees "Logging in.." string;
  3. User waits for string to disappear;
  4. User is in MainActivity and sees "You're logged in"

testLogin source:

    public void testLogin() throws Exception{
    onView(withId(R.id.login_email)).perform(typeText(LOGIN_EMAIL));
    onView(withId(R.id.login_password)).perform(typeText(LOGIN_PASSWORD));
    onView(withId(R.id.login_loginBtn)).perform(click());
    onView(withText(R.string.loading_logging_in)).check(matches(isDisplayed()));
    onView(withText("You're logged in")).check(matches(isDisplayed()));
}

The problem was that espresso didn't wait for "You"re logged in" string to appear, it was trying to find it while logging still was in process.

logcat:

com.google.android.apps.common.testing.ui.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "You're logged in"

I've tried using Thread.sleep(10000), but it terminates the run on Thread.sleep(10000) and gives me error:

Test failed to run to completion. Reason: 'Instrumentation run failed due to 'Process crashed.''. Check device logcat for details Test running failed: Instrumentation run failed due to 'Process crashed.'

logcat:

@@@ @@@ @@@was killed cancelService in HttpReRegistrationService

Before that, I used the waitForActivity(MainActivity.class) method. Is there any workaround to make this work?

4

2 回答 2

2

如果您的登录过程在尝试登录用户时很忙,并且您没有使用 AsyncTask(以适当的方式),那么您唯一的选择是让您的繁忙资源来实现此处IdlingResource所述的接口。

这样,Espresso 就知道等待的时间和时间。

于 2014-08-28T22:44:17.090 回答
2

解决此问题的另一种方法是使用 UiAutomator。我经常在这种情况下使用它。解决方案将是这样的:

UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

onView(withId(R.id.login_loginBtn)).perform(click());

UiObject loginLoading = mDevice.findObject(new UiSelector().resourceId(your_package_name+":id/loading_logging_in"));
loginLoading.waitUntilGone(15 * 1000); //Give them 15s to login

onView(withText("You're logged in")).check(matches(isDisplayed()));

或者你甚至可以这样做:

UiObject loginButton = mDevice.findObject(new UiSelector().resourceId(your_package_name+":id/login_loginBtn"));

loginButton.clickAndWaitForNewWindow(15 * 1000); //Again at least 15s to login
于 2017-05-09T11:23:18.343 回答