Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NPE when getSystemService called in a Service instance by Robolectric

When I tried to call getSystemService in a Service instance, it threw a NPE. It's called in onCreate:

Vibrator  vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

And I created the Service instance like this:

@Test
public void test() throws Exception{
    FooService service = new FooService();
    service.oncreate();//NPE in this line
    //... intent declaration
    service.onStartCommand(intent, 0, 1);
}

But when I tried to modify my original code from getSystemService, which was called by the Service instance itslef, to xxApplication.getSystemService(XXX), which was called by application, it didn't throw any Exception. So, how can I test a service properly without modifying my original code?

like image 907
Light Avatar asked Nov 25 '25 20:11

Light


1 Answers

@Test
public void test() throws Exception {
    ServiceController<FooService> serviceController = Robolectric.buildService(FooService.class);
    // ... intent declaration.
    serviceController.attach()  // Calls service.attach()
      .create() // Calls service.onCreate()
      .withIntent(intent)
      .startCommand(0, 1); // Calls service.onStartCommand(intent, 0, 1)
}

The key point is to call attach() before onCreate(). Anyone doesn't know how to create a Service instance correctly can see this issue.

like image 135
Light Avatar answered Nov 28 '25 14:11

Light



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!