简体   繁体   中英

How to test remote android aidl service

I have a small app that interacts with a remote android service. I would like to mock that service in unit tests. I use Robolectric and JUnit for other test cases and shadows but I could not figure how to deal with remote services.

Is it sufficient to create and start a test service using the same package with the real service and export methods using same aidl ?

Since I don't have the code for that service, I assume that I can not use Robolectric 's ShadowService which requires actual class to be there.

Thanks a lot.

I would use Mockito to create a Mock of the interface and then pass that instance to your code in your tests. You could also manually create an implementation of that interface in your test code and use that.

So you have to do the mocking yourself and it is important that the code you want to tests uses some form of dependency injection to aquire a reference to the aidl interface, so you can pass your own mock in your tests.

If you want to write a unit test for service then you can use Mockito for mocking service behavior.If you want to test your service on the real device then this is how you can connect with your service.

@RunWith(AndroidJUnit4.class)
public classRemoteProductServiceTest {
    @Rule
    public final ServiceTestRule mServiceRule = new ServiceTestRule();
    @Test
    public void testWithStartedService() throws TimeoutException {
        mServiceRule.startService(
                new Intent(InstrumentationRegistry.getTargetContext(), ProductService.class));
        //do something
    }
    @Test
    public void testWithBoundService() throws TimeoutException, RemoteException {
        IBinder binder = mServiceRule.bindService(
                new Intent(InstrumentationRegistry.getTargetContext(), ProductService.class));
        IRemoteProductService iRemoteProductService = IRemoteProductService.Stub.asInterface(binder);
        assertNotNull(iRemoteProductService);
        iRemoteProductService.addProduct("tanvi", 12, 12.2f);
     assertEquals(iRemoteProductService.getProduct("tanvi").getQuantity(), 12);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM