NullpointerException при остановке службы в ServiceTestCase
Я тестирую свой сервис с помощью ServiceTestCase
,
public class MyTest extends ServiceTestCase<MyService>{
private Context mContext;
private Intent intent;
public MyTest(){
super(MyService.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
mContext = this.getContext();
intent = new Intent(mContext, MyService.class);
}
@MediumTest
public void runMyTest(){
startService(intent);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
MyService service = getService();
//line 33, NullpointerException here, why?
mContext.stopService(intent);
}
}
Но когда я запускаю свой тест, я постоянно получаю NullPointerException при вызове stopService(intent)
в tearDwon()
Перезвоните. Зачем?
Трассировки стека:
java.lang.NullPointerException
at com.my.app.test.MyTest.tearDown(MyTest.java:33)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584)
2 ответа
Вы получаете mContext
как null
,
Пытаться
mContext = getSystemContext();
вместо
mContext = this.getContext();
So that it becomes,
@Override
public void setUp() throws Exception {
super.setUp();
mContext = getSystemContext();
intent = new Intent(); // the intent created this way can not be null.
intent.setClass(mContext , MyService.class);
}
Вместо getContext() try, getSystemContext();
Согласно документации
Возвращает реальный системный контекст, который сохраняется setUp(). Используйте его для создания фиктивных или других типов объектов контекста для тестируемой службы.