Android - testing if another activity has started

梦想的初衷 提交于 2019-12-10 18:49:02

问题


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:


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.



来源:https://stackoverflow.com/questions/5945677/android-testing-if-another-activity-has-started

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!