我正在嘗試使用JUNIT4爲Android服務編寫單元測試。 繼我的服務代碼:使用Junit的單元測試服務4
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()'null對象引用
請問您可以請教一下我的問題是什麼? P.S - 我知道如何使用Junit3與ServiceTestCase做到這一點,但我想這樣做與Junit4
感謝, Zachi