我正在使用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()
。为什么?
Stacktrace:
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)
发布于 2013-09-11 00:35:07
你得到了mContext
作为null
。
试一试
mContext = getSystemContext();
而不是
mContext = this.getContext();
所以它变成了,
@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);
}
发布于 2013-09-11 00:36:47
而不是getContext() try,而是getSystemContext();
根据文件
返回由setUp()保存的真实系统上下文。使用它为被测试的服务创建模拟或其他类型的上下文对象。
https://stackoverflow.com/questions/18736102
复制相似问题