android-测试最近启动的活动是否实际上已经开始

我在SO上研究了一些类似的问题,但是还没有成功地对此进行测试.

Android – testing if another activity has started

我尝试过这个,但是对我来说,origactivity结果为null,所以我使用.baseIntent.getComponent()来标识启动的活动(我想这应该给我同样的结果?)

我的JUnit测试代码:

public class MainMenuTest extends
        ActivityInstrumentationTestCase2<MainMenuActivity> {

    public MainMenuTest() {
        super("package.name", MainMenuActivity.class);
    }

    private MainMenuActivity mActivity;
    private ActivityManager am;

    public void setUp() throws Exception {
        super.setUp();
        mActivity = this.getActivity();
        am = (ActivityManager) mActivity.getSystemService(Service.ACTIVITY_SERVICE);
        Intent i = new Intent(mActivity, GameActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mActivity.startActivity(i);
    }

    public void testNewGameButton() {
        final ActivityManager am2 = am;

        mActivity.runOnUiThread(new Runnable() {
            public void run() {                 
                List<ActivityManager.RecentTaskInfo> processes = am2.getRecentTasks(2, ActivityManager.RECENT_WITH_EXCLUDED);
                ActivityManager.RecentTaskInfo recentTask = processes.get(0);
                assertEquals(recentTask.baseIntent.getComponent().getClassName(), GameActivity.class.getName());
            }
        });
    }
}

不幸的是,这导致assertEquals(recentTask.baseIntent.getComponent().getClassName(),断言失败.

为什么会这样,有没有更好的方法来测试呢?

最佳答案
断言失败是因为ActivityManager.getRecentTasks(…)返回导致创建新task的活动,在您的情况下为MainMenuActivity,而不是GameActivity.您可以使用Instrumentation.ActivityMonitor,如下所示:

public class MainMenuTest extends
        ActivityInstrumentationTestCase2<MainMenuActivity> {

    public MainMenuTest() {
        super("package.name", MainMenuActivity.class);
    }

    private MainMenuActivity mActivity;
    private ActivityMonitor mGameActivityMonitor;

    public void setUp() throws Exception {
        super.setUp();
        mActivity = this.getActivity();
        Intent i  = new Intent(mActivity,
                GameActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add a monitor before we start the activity
        mGameActivityMonitor = 
                new ActivityMonitor(GameActivity.class.getName(), null, false);
        getInstrumentation().addMonitor(mGameActivityMonitor);

        mActivity.startActivity(i);
    }

    public void testNewGameButton() {
        // Use the monitor to ensure the activity was started
        Activity activity = mGameActivityMonitor.waitForActivityWithTimeout(5 * 1000);
        assertNotNull("Activity was not started", activity);
    }
}

转载注明原文:android-测试最近启动的活动是否实际上已经开始 - 代码日志