2

我有一项服务,我正在尝试使用 ServiceTestCase 进行单元测试。在我的 setUp() 中,我正在创建 IBinder,但是在创建意图时我得到了 NullPointerException。我正在使用应用程序的上下文并将其设置为测试用例,但包名称似乎为空。关于它为什么这样做以及解决方案可能是什么的任何想法?

服务测试用例代码:

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)
4

1 回答 1

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.

希望这可以帮助。

于 2013-07-11T03:48:11.437 回答