我有一个正在尝试使用ServiceTestCase进行单元测试的服务。在我的setUp()中,我创建了IBinder,但是在创建intent时得到了一个NullPointerException。我使用应用程序的上下文并将其设置为测试用例,但包名称似乎为空。有没有什么想法可以解释为什么要这样做,以及解决方案是什么?
ServiceTestCase代码:
public class MyActivityTest extends ServiceTestCase<ImageDownloadTaskService> {
ImageDownloadTaskService service;
/**
* Constructor
*/
public MyActivityTest() {
super(ImageDownloadTaskService.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setApplication(new MyApplication());
getApplication().onCreate();
setContext(getApplication());
Intent intent = new Intent(getContext(), ImageDownloadTaskService.class);
IBinder binder = bindService(intent);
service = ((ImageDownloadTaskService.LocalBinder) binder).getService();
}
public void testService(){
assertTrue(service.returnTrue());
}
}服务代码片段:
public boolean returnTrue(){
return true;
}
public class LocalBinder extends Binder {
ImageDownloadTaskService getService() {
return ImageDownloadTaskService.this;
}
}
private final IBinder binder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}错误:
java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3004)
at com.example.untitled2.MyActivityTest.setUp(MyActivityTest.java:43)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)发布于 2013-07-11 11:48:11
尝试使用getSystemContext()而不是getContext()。医生说:
It returns the real system context that is saved by setUp(). Use it to create mock or other types of context objects for the service under test.
希望这能有所帮助。
https://stackoverflow.com/questions/17579988
复制相似问题