Test a HostApduService with Robolectric

539 views Asked by At

I want to test my HostApduService with a Robolectric test but I can't find a way to test my service. The normal approach for testing a Service doesn't 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
    }
}

Example HostApduservice

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.

1

There are 1 answers

0
Michal On

I've used Espresso Test Framework from android support libraries. Here is how my basic test looks like that provides 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 how 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'
}