Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso waitFor.. and Thread.sleep() solution

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?

like image 284
Oleg Nikolaev Avatar asked Sep 30 '22 20:09

Oleg Nikolaev


1 Answers

If your login process is busy while trying to log in the user and you're not using AsyncTask (in an appropriate way) your only option is to have your busy resource to implement the interface IdlingResource as described here.

That way Espresso knows when and how long to wait.

like image 137
Androiderson Avatar answered Oct 20 '22 11:10

Androiderson