Espresso.pressBack()不调用onBackPressed()

时间:2017-03-17 15:17:04

标签: android android-espresso

在Espresso课程中:

 @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();

}

活动:

finish()

当我调用Espresso测试方法时,执行将直接转到Activity

当我在onBackPressed()按下后退按钮(用我的手)时,首先执行finish(),然后执行onBackPressed()。 如何使用Espresso测试函数 @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(); } ? 谢谢!

编辑: 这是我的错误。问题是在我想调用pressBack的Activity中,屏幕键盘被打开了。当软键盘打开时,按下按钮不会调用onBackPressed,而是使键盘不显示。我尝试连续使用两个pressBack()并且它正常工作:

remove_action( ‘woocommerce_before_main_content’,‘woocommerce_output_content_wrapper’, 10);

add_action(‘woocommerce_before_main_content’, ‘my_content_wrapper_start’, 10);
function my_content_wrapper_start() {
...
}

2 个答案:

答案 0 :(得分:26)

如果您不在根活动中,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();

答案 1 :(得分:1)

@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()));
}