Android单元测试 - 如何使用ServiceTestCase测试服务

时间:2015-04-13 15:49:39

标签: java android unit-testing android-service android-instrumentation

我在Android Studio中为服务创建单元测试时遇到问题。我已经设置了我的项目来执行单元测试,并成功地为不同的(非服务)类设置了测试。我可以运行这些测试并让它们通过。

这是我的ServiceTestCase的代码:

package com.roche.parkinsons.service;

import android.content.Intent;
import android.test.ServiceTestCase;
import android.util.Log;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class GeneralServiceTest extends ServiceTestCase<GeneralService> {

    /** Tag for logging */
    private final static String TAG = GeneralServiceTest.class.getName();

    public GeneralServiceTest() {
        super(GeneralService.class);
    }
//
    @Before
    public void setUp() throws Exception {
        super.setUp();

        Log.d(TAG, "Setup complete");
    }

    @After
    public void tearDown() throws Exception {
        Log.d(TAG, "Teardown complete");


        super.tearDown();
    }

    @Test
    public void testOnCreate() throws Exception {
        Intent intent = new Intent(getSystemContext(), GeneralService.class);
        startService(intent);
        assertNotNull(getService());

    }

}

正如你所看到的,它就像我能做到的一样简单。无论我尝试什么,assertNotNull总是失败。

通过调试测试,我发现创建的意图是:

Intent intent = new Intent(getSystemContext(), GeneralService.class);

始终返回null。

我尝试过像这样设置上下文和类

    public void testOnCreate() throws Exception {
        Intent intent = new Intent(getSystemContext(), GeneralService.class);
        intent.setClass(getSystemContext(), GeneralService.class);
        startService(intent);
        assertNotNull(getService());

    }

但这没有效果。

我没有想法。很少有ServiceTestCase的例子已经过时,而且我已经找到了(例如:http://alvinalexander.com/java/jwarehouse/android-examples/samples/android-9/ApiDemos/tests/src/com/example/android/apis/app/LocalServiceTest.java.shtml)我试图尽可能地复制他们的代码并且没有成功

我认为我可能需要在设备或模拟器上运行单元测试,但这对我的其他单元测试没有成功。

总之,为什么我尝试创建一个始终返回null的意图?

0 个答案:

没有答案
相关问题