Android - testing if another activity has started

2019-07-06 09:21发布

I am trying to test the following scenario, enter a letter in the autocomplete textview, scroll down and select one of the options, then click a button, The button click starts a new activity. I want to check if the new activity has begun or not. This is the test method.

public void testSpinnerUI() {

    mActivity.runOnUiThread(new Runnable() {
        public void run() {

            mFromLocation.requestFocusFromTouch(); // use reqestFocusFromTouch() and not requestFocus()
        }
    });
    //set a busstop that has W in it, and scroll to the 4th position of the list - In this case Welcome
    this.sendKeys(KeyEvent.KEYCODE_W);
    try {
        Thread.sleep(2000); //wait for 2 seconds so that the autocomplete loads
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    for (int i = 1; i <= 4; i++) {
      this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
    }

    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);

    assertEquals("Welcome", mFromLocation.getText().toString());

    //hit down arrow twice and centre button

    this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
    this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);

    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);

    assertEquals(com.myApp.RouteListActivity.class, getActivity());

}

The test fails at the last assertEquals(com.myApp.RouteListActivity.class, getActivity()). Can you please guide me on how to test if the new activity has been started or not?

1条回答
贪生不怕死
2楼-- · 2019-07-06 09:33

You'll need to use the ActivityManager as conveniently demonstrated here: https://stackoverflow.com/questions/3908029/android-get-icons-of-running-activities

The short summary:

ActivityManager am = (ActivityManager) getSystemService(Service.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> processes = am.getRecentTasks(5);

gets you a list of all the running processes (you'll need the GET_TASKS permission). You can search through that list for your Activity: one of those tasks should have an origActivity property with the same name as your Activity.

查看更多
登录 后发表回答