0

我正在使用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)
4

2 回答 2

1

你得到mContextnull

尝试

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-11T08:35:07.790 回答
0

代替 getContext() 尝试,getSystemContext();

根据文档

返回由 setUp() 保存的真实系统上下文。使用它为被测服务创建模拟或其他类型的上下文对象。

于 2013-09-11T08:36:47.770 回答