Java Android单元测试-如何使用ServiceTestCase测试服务
我在Android Studio中为服务创建单元测试时遇到问题。我已经设置了我的项目来执行单元测试,并且已经成功地为不同的(非服务)类设置了测试。我可以运行这些测试并让它们通过 这是我的ServiceTestCase的代码:Java Android单元测试-如何使用ServiceTestCase测试服务,java,android,unit-testing,android-service,android-instrumentation,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; impo
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());
}
}
始终返回null
我尝试过这样设置上下文和类
public void testOnCreate() throws Exception {
Intent intent = new Intent(getSystemContext(), GeneralService.class);
intent.setClass(getSystemContext(), GeneralService.class);
startService(intent);
assertNotNull(getService());
}
但这没有效果
我没有主意了。对于ServiceTestCase,很少有不过时的例子,在我找到的例子中(比如这里),我尝试尽可能地复制它们的代码,但没有成功
我的理论是,我可能需要在设备或模拟器上运行单元测试,但这对于我其他成功的单元测试来说并不是必需的
总之,为什么我试图创建的意图总是返回null?我也有同样的问题,但在您从中复制的示例中,它们明确指出:*要运行此测试,您可以键入:*adb shell am instrument-w\*-e class com.example.android.api.app.LocalServiceTest\*com.example.android.api.tests/android.test.InstrumentationTestRunner,表示他们在模拟器或设备上运行它。我真的很好奇,在没有模拟器的情况下,您是如何让其他单元测试运行的,它们是基本的Junit测试还是android测试?在您的测试用例运行时,您的服务可能不会启动。我搜索了很多,在服务测试中找不到很多样本。但这帮助我理解了测试服务背后的概念。事实证明,我误解了这个概念——我运行的是仪器测试,而不是在设备上,这就是为什么我无法运行服务的原因。为了测试服务,我需要设置并运行需要部署到设备的检测测试。注意!我的答案被删除了,因为它是“重复的”,让我们试试评论。ServiceTestCase已弃用,无法按预期工作。
public void testOnCreate() throws Exception {
Intent intent = new Intent(getSystemContext(), GeneralService.class);
intent.setClass(getSystemContext(), GeneralService.class);
startService(intent);
assertNotNull(getService());
}