简体   繁体   中英

How can i simulate a Back-Button click

so i was working with Robotium to automate tests and i'm having a little problem. Robotium is able to "sendkey(keyevent.keycode_back)" so i can return from a view to the previous but now there is another (android native) activity which opens when i click on "forgotten password" (hyperlink) and i would require android itself to simulate a back button click. is there a way to do so?

As for the code i'm working on:

@FlakyTest(tolerance = 2)
public void testperformMsgListItemandItemSelectTestAfterStartInLandscape_ShouldSucceed() throws Exception{
    try {

        mSolo.clickOnText("Forgotten Password?");
        assertFalse(mSolo.getCurrentActivity().hasWindowFocus());
        mSolo.sendKey(KeyEvent.KEYCODE_HOME);
        assertTrue(mSolo.getCurrentActivity().hasWindowFocus());
        mSolo.clickOnText("Register Now!");
        assertFalse(mSolo.getCurrentActivity().hasWindowFocus());

    } catch (AssertionError err) {
        mSolo.fail(getName(), err);
        throw err;
    }
}

Create a KeyEvent and dispatch it.

For example:

KeyEvent kdown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
Activity.dispatchKeyEvent(kdown);

an alternative method is to just call finish() in your activity. That disposes of the current activity and takes you back to the previous activity, which is exactly what the Android OS does when you click the back button.

If the current activity belongs to the app you're testing, use

mSolo.goBack();

Robotium cannot perform any actions if the current activity belongs to another app, so to write useful tests you can't ever let your tests launch other apps.

if >=API LEVEL5:

   super.onBackPressed()

else

    KeyEvent kdown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
    Activity.dispatchKeyEvent(kdown);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM