Lig*_*ght 3 testing android robolectric
当我试图在Service实例中调用getSystemService时,它抛出了一个NPE.它在onCreate中调用:
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
Run Code Online (Sandbox Code Playgroud)
我创建了这样的Service实例:
@Test
public void test() throws Exception{
FooService service = new FooService();
service.oncreate();//NPE in this line
//... intent declaration
service.onStartCommand(intent, 0, 1);
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将我的原始代码从服务实例itlef调用的getSystemService修改为xxApplication.getSystemService(XXX)时,它被应用程序调用,它没有抛出任何异常.那么,如何在不修改原始代码的情况下正确测试服务?
@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)
}
Run Code Online (Sandbox Code Playgroud)
关键是attach()要先打电话onCreate().任何人都不知道如何正确创建一个Service实例可以看到这个问题.
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |