【问题标题】:How can I unit test that my Android Service launched a particular Activity?如何对我的 Android 服务启动特定活动进行单元测试?
【发布时间】:2015-06-28 00:55:54
【问题描述】:

根据this other question,可以从Service 开始Activity

如何在ServiceTestCase 中进行单元测试以确保将正确的Intent 传递给startActivity()

ActivityUnitTestCase 有一个有用的方法getStartedActivityIntent()。我已经能够测试相反的情况——ActivityActivityUnitTestCase 中启动了Service,方法是将ContextWrapper 传递到它的setActivityContext() 方法中,就像在this other question 中一样。

但是ServiceTestCase 似乎没有getStartedActivityIntent()setActivityContext() 的等价物,这对我有帮助。我能做什么?

【问题讨论】:

    标签: android android-intent android-activity android-service android-testing


    【解决方案1】:

    原来答案就在the docs for ServiceTestCase

    相当于setActivityContext(),它被称为setContext()。因此,您可以调用getContext(),用ContextWrapper 包装上下文,然后调用setContext(),就像使用ActivityUnitTestCase 一样。例如:

    private volatile Intent lastActivityIntent;
    
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        setContext(new ContextWrapper(getContext()) {
            @Override
            public void startActivity(Intent intent) {
                lastActivityIntent = intent;
            }
        });
    }
    
    protected Intent assertActivityStarted(Class<? extends Activity> cls) {
        Intent intent = lastActivityIntent;
        assertNotNull("No Activity started", intent);
        assertEquals(cls.getCanonicalName(), intent.getComponent().getClassName());
        assertTrue("Activity Intent doesn't have FLAG_ACTIVITY_NEW_TASK set",
                (intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0);
        return intent;
    }
    

    【讨论】:

    • 所以这只是我的一个愚蠢的错误,没有注意到明显命名的 setContext() 方法,但我想我会留下它以防它对其他人有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2012-05-26
    • 2011-02-25
    相关资源
    最近更新 更多