Espresso.pressBack () does not call onBackPressed ()

In the Espresso class:

 @Rule
    public IntentsTestRule<MainActivity> mIntentsRule = new IntentsTestRule<>(
            MainActivity.class);

@Test
public void test_backButton(){
onView(withId(R.id.NEXT_ACTIVITY)).perform(scrollTo(), click());

Espresso.pressBack();
}

In action:

 @Override
public void onBackPressed() {
    Log.d("TEST_pressBack", "inside onBackPressed()");
    do_something();
    super.onBackPressed();

}
   @Override
public void finish() {
    Log.d("TEST_pressBack", "inside finish()");
    super.finish();

}

When I call the Espresso test method, execution jumps directly to finish().

When I press the back button (with my hand) in Activity, execution is done first in onBackPressed(), and then before finish(). How to test a function onBackPressed()on Espresso? Thanks!

EDIT: This is my mistake. The problem was that in Activity, in which I wanted to call pressBack, an on-screen keyboard was opened. When the soft keyboard is open, the button does not call onBackPressed, but the keyboard does not appear instead. I tried with two keystrokes () in a line, and it worked correctly:

    @Rule
    public IntentsTestRule<MainActivity> mIntentsRule = new IntentsTestRule<>(
            MainActivity.class);

@Test
public void test_backButton(){
onView(withId(R.id.NEXT_ACTIVITY)).perform(scrollTo(), click());

Espresso.pressBack();

//The extra pressBack()
Espresso.pressBack();

}
+6
source share
2

, Espresso.pressBack() , , . :

  /**
  * Press on the back button.
  *
  * @throws PerformException if currently displayed activity is root activity, since pressing back
  *         button would result in application closing.
  */
  public static void pressBack() {
        onView(isRoot()).perform(ViewActions.pressBack());
  }

, , , . , ui-automator (ui-automator espresso):

gradle:

androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.2'

:

UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
mDevice.pressBack();
+5

@billst, , , ViewAction.closeSoftKeyboard() , .

@Test
public void afterStartedEditing_dialogDisplayed_when_home_or_back_pressed() {
    //find view
    onView(withId(R.id.add_pet_breed))
            .perform(click())
            .perform(closeSoftKeyboard());
    onView(isRoot()).perform(pressBack());

    //check assertion
    onView(withText(R.string.discard))
            .check(matches(isDisplayed()));
}
0

Source: https://habr.com/ru/post/1015834/


All Articles