ServiceTestCase中的stopService时的NullpointerException

时间:2013-09-11 08:21:43

标签: android performance android-intent android-testing 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); 
  }

}

但是当我运行测试时,在stopService(intent)回调中调用tearDwon()时,我会不断获得 NullPointerException 。为什么呢?

堆栈跟踪:

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 个答案:

答案 0 :(得分: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);

   }

答案 1 :(得分:0)

而不是getContext()try,getSystemContext();

根据文件

  

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