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.
aidl file, the Android SDK tools generate an IBinder interface based on the . aidl file and save it in the project's gen/ directory. The service must implement the IBinder interface as appropriate. The client applications can then bind to the service and call methods from the IBinder to perform IPC.
'Stub' is a class that implements the remote interface in a way that you can use it as if it were a local one. It handles data marashalling/unmarshalling and sending/receiving to/from the remote service.
all native Java data types like int,long, char and Boolean.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With