首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NullpointerException时间stopService in ServiceTestCase

NullpointerException时间stopService in ServiceTestCase
EN

Stack Overflow用户
提问于 2013-09-11 08:21:43
回答 2查看 860关注 0票数 0

我正在使用ServiceTestCase测试我的服务。

代码语言:javascript
复制
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:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2013-09-11 08:35:07

你得到了mContext作为null

试一试

代码语言:javascript
复制
mContext =  getSystemContext();

而不是

代码语言:javascript
复制
mContext = this.getContext();

所以它变成了,

代码语言:javascript
复制
@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
EN

Stack Overflow用户

发布于 2013-09-11 08:36:47

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

根据文件

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18736102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档