我在为 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?