I'm trying to use Robolectric to test a NFC helper class. Simplified, I'm doing something like this:
Activity activity = Robolectric.buildActivity(Activity.class)
.create()
.start()
.resume()
.get();
NfcAdapter nfcAdapter = ShadowNfcAdapter.getNfcAdapter(activity);
and then exercise my NFC helper class as it does something like this:
if (!nfcAdapter.isEnabled()){
//more stuff
}
However, calling nfcAdapter.isEnabled() causes a null pointer exception.
java.lang.NullPointerException
at android.nfc.NfcAdapter.isEnabled(NfcAdapter.java:621)
at <package>.test_NfcIntent_shouldPostToBus(NfcHelperTest.java:49)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
The exception looks to be coming from Android's NfcAdapter.java
public boolean isEnabled() {
try {
return sService.getState() == STATE_ON;
} catch (RemoteException e) {
attemptDeadServiceRecovery(e);
return false;
}
}
where sService is null. Indeed, when I use the debugger I can see that nfcAdapter's fields are all either null or objects which themselves have null fields.
Is this the correct way to be using ShadowNfcAdapter? Alternatively, what would be the correct way to test that a NFC helper class is doing the correct things when it is triggered?
Aucun commentaire:
Enregistrer un commentaire