测试最近启动的活动是否实际开始

时间:2011-10-12 09:23:42

标签: android junit

我已经在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(),断言失败。

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

1 个答案:

答案 0 :(得分:3)

断言失败是因为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);
    }
}