我有一项服务,我正在尝试使用ServiceTestCase进行单元测试。在我的setUp()中,我正在创建IBinder,但是在创建intent时我得到NullPointerException。我正在使用应用程序的上下文并将其设置为测试用例,但包名称似乎为null。关于它为什么这样做以及解决方案可能是什么的任何想法?
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)
答案 0 :(得分:3)
尝试使用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.
希望这有帮助。