【发布时间】:2015-12-16 13:08:16
【问题描述】:
我正在尝试使用 JUNIT4 为 Android 服务编写单元测试。 按照我的服务代码:
class myService extends Service {
// Binder given to clients
private IBinder mBinder = null;
@Override
public void onCreate() {
super.onCreate();
mBinder = new LocalBinder();
}
public int multiply(int x, int y){
return (x*y);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public myService getService() {
// Return this instance of LocalService so clients can call public methods.
return myService.this;
}
}
}
还有我的单元测试代码:
public class testServiceUlt {
@Rule
public final ServiceTestRule mServiceRule = new ServiceTestRule();
@Test
public void testWithBoundService() throws TimeoutException, InterruptedException {
// Create the service Intent.
Intent serviceIntent =
new Intent(InstrumentationRegistry.getTargetContext(), myService.class);
// Bind the service and grab a reference to the binder.
IBinder binder = mServiceRule.bindService(serviceIntent);
// Get the reference to the service, or you can call public methods on the binder directly.
myService service = ((myService.LocalBinder) binder).getService();
int val = service.multiply(80, 0);
assertEquals("should be zero", 0, val);
}
}
问题是活页夹是空的,我收到以下错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'com.example.xxx.xxx.xxx com.example.xxx.xxx.xxx$LocalBinder.getService()'
你能告诉我我的问题是什么吗? P.S - 我知道如何将 Junit3 与 ServiceTestCase 一起使用,但我想使用 Junit4
谢谢, 扎奇
【问题讨论】:
标签: android unit-testing junit4