2

ServiceTestCase を使用して単体テストしようとしているサービスがあります。setUp() で IBinder を作成していますが、インテントの作成時に 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)
4

1 に答える 1

3

getContext() の代わりにgetSystemContext()を使用してみてください。ドキュメントは言う:

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 に答える