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?
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With