NullpointerException when stopService in ServiceTestCase

871 Views Asked by At

I am testing my service by using 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); 
  }

}

But when I run my test, I constantly get NullPointerException when call stopService(intent) in tearDwon() callback. Why?

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)
2

There are 2 best solutions below

4
Ritesh Gune On

You are getting mContext as null.

Try

mContext =  getSystemContext();

instead of

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);

   }
1
prijupaul On

Instead of getContext() try, getSystemContext();

As per the documentation

Returns the real system context that is saved by setUp(). Use it to create mock or other types of context objects for the service under test.