简体   繁体   English

如何测试远程android aidl服务

[英]How to test remote android aidl service

I have a small app that interacts with a remote android service. 我有一个与远程android服务交互的小应用程序。 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. 我将RobolectricJUnit用于其他测试用例和阴影,但我无法想象如何处理远程服务。

Is it sufficient to create and start a test service using the same package with the real service and export methods using same aidl ? 是否足以使用相同的包创建和启动测试服务,使用相同的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. 由于我没有该服务的代码,我认为我不能使用RobolectricShadowService ,它需要实际的类。

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. 我会使用Mockito创建一个接口模拟,然后将该实例传递给测试中的代码。 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. 因此,您必须自己进行模拟,并且您希望测试的代码使用某种形式的依赖注入来获取对aidl接口的引用非常重要,因此您可以在测试中传递自己的模拟。

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. 如果您想为服务编写单元测试,那么您可以使用Mockito来模拟服务行为。如果您想在真实设备上测试您的服务,那么这就是您可以如何连接您的服务。

@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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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