Test HostApduService with Robolectric
I want to test my HostApduService with the Robolectric test but can't find a way to test my service. Normal service testing method does not work with HostApduServices. Any suggestions?
What I've tried so far:
Example Normal service
public class MyNormalService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void doStuff(){
// Logic
}
}
HostApduservice example
public class MyHostApduService extends HostApduService {
@Override
public byte[] processCommandApdu(final byte[] commandApdu, Bundle extras) {
// Do my stuff
}
}
Tests
@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class MyHostApduServiceTest {
@Test
public void testNormalService(){ // Succeeds
MyNormalService service = new MyNormalService();
assertNotNull(service);
}
@Test
public void testProcessCommandApdu1(){ // Fails
MyHostApduService service = new MyHostApduService();
assertNotNull(service);
}
@Test
public void testProcessCommandApdu2(){ // Fails
MyHostApduService service = Robolectric.buildService(MyHostApduService.class).create().get();
assertNotNull(service);
}
@Test
public void testProcessCommandApdu3(){ // Fails
MyHostApduService service = Robolectric.setupService(MyHostApduService.class);
assertNotNull(service);
}
}
All apdu tests result in the same error:
java.lang.RuntimeException: Stub!
at android.nfc.cardemulation.HostApduService.__constructor__(HostApduService.java)
at android.nfc.cardemulation.HostApduService.<init>(HostApduService.java:5)
at com.abc.MyHostApduService.<init>(MyHostApduService.java:
testNormalService succeeds.
+3
source to share
1 answer
I used Espresso test framework from Android Support Libraries. This is what my basic test looks like, which ensures a successful result:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class HostApduServiceTest {
@Rule
public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
@Test
public void testService() throws Throwable {
uiThreadTestRule.runOnUiThread(new Runnable() {
@Override
public void run() {
MyHostApduService service = new MyHostApduService();
Assert.assertNotNull(service);
}
});
}
}
This is what the corresponding android dependencies look like:
testCompile 'junit:junit:4.12'
compile 'com.android.support:support-annotations:23.1.1'
androidTestCompile ('com.android.support.test:runner:0.5'){
exclude module: 'support-annotations'
}
androidTestCompile ('com.android.support.test.espresso:espresso-core:2.2.2'){
exclude module: 'support-annotations'
}
0
source to share