【问题标题】:Android - testing if another activity has startedAndroid - 测试另一个活动是否已经开始
【发布时间】:2011-08-22 04:29:21
【问题描述】:

我正在尝试测试以下场景,在自动完成文本视图中输入一个字母,向下滚动并选择其中一个选项,然后单击一个按钮,单击按钮会启动一个新活动。我想检查新活动是否已经开始。这是测试方法。

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

}

测试在最后一个 assertEquals(com.myApp.RouteListActivity.class, getActivity()) 处失败。能否请您指导我如何测试新活动是否已开始?

【问题讨论】:

    标签: android junit3


    【解决方案1】:

    您需要使用ActivityManager,如下所示:https://stackoverflow.com/questions/3908029/android-get-icons-of-running-activities

    简短的总结:

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

    为您提供所有正在运行的进程的列表(您需要 GET_TASKS 权限)。您可以在该列表中搜索您的 Activity:其中一项任务应具有与您的 Activity 同名的 origActivity 属性。

    【讨论】:

    • 嗨,我刚试过这个,我给了测试项目 GET_TASKS 权限,但我得到了一个例外,说我没有权限。如果我将权限移至我正在测试的实际应用程序,它就可以工作。但这并不理想。该应用程序不需要测试应有的权限。这是正常的吗?我做错了吗?
    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多