2014-06-06 2 views
3

서비스 인스턴스에서 getSystemService를 호출하려고하면 NPE가 발생합니다. 그것은에서 onCreate에서라고 :Robolectric이 서비스 인스턴스에서 getSystemService를 호출 할 때 NPE

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) : 응용 프로그램에서 호출되었지만 Exception을 throw하지 않았습니다. 그럼 원래 코드를 수정하지 않고 어떻게 서비스를 제대로 테스트 할 수 있습니까?

답변

5
@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) 
} 

요점은 onCreate() 전에 attach()으로 전화하는 것입니다. 서비스 인스턴스를 올바르게 작성하는 방법을 모르는 사람은 누구나 issue을 볼 수 있습니다.

관련 문제