Android Robolectric在服务实例中调用getSystemService时的NPE

Android Robolectric在服务实例中调用getSystemService时的NPE,android,testing,robolectric,Android,Testing,Robolectric,当我试图在服务实例中调用getSystemService时,它抛出了一个NPE。它在onCreate中调用: Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 我创建了如下的服务实例: @Test public void test() throws Exception{ FooService service = new FooService(); service.oncreate();//NP

当我试图在服务实例中调用getSystemService时,它抛出了一个NPE。它在onCreate中调用:

Vibrator  vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
我创建了如下的服务实例:

@Test
public void test() throws Exception{
    FooService service = new FooService();
    service.oncreate();//NPE in this line
    //... intent declaration
    service.onStartCommand(intent, 0, 1);
}
但当我试图将原始代码从由服务实例itslef调用的getSystemService修改为由应用程序调用的xxApplication.getSystemService(XXX)时,它没有引发任何异常。 那么,如何在不修改原始代码的情况下正确测试服务呢?

@test
@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)
}
public void test()引发异常{ ServiceController-ServiceController=Robolectric.buildService(FooService.class); //……意图声明。 serviceController.attach()//调用service.attach() .create()//调用service.onCreate() .故意 .startCommand(0,1);//调用service.onStartCommand(intent,0,1) }
关键是在
onCreate()之前调用
attach()
。 任何不知道如何正确创建服务实例的人都可以看到这一点