[英]How to test remote android aidl service
我有一个与远程android
服务交互的小应用程序。 我想在单元测试中模拟该服务。 我将Robolectric和JUnit
用于其他测试用例和阴影,但我无法想象如何处理远程服务。
是否足以使用相同的包创建和启动测试服务,使用相同的aidl
实际服务和导出方法?
由于我没有该服务的代码,我认为我不能使用Robolectric
的ShadowService ,它需要实际的类。
非常感谢。
我会使用Mockito创建一个接口模拟,然后将该实例传递给测试中的代码。 您还可以在测试代码中手动创建该接口的实现并使用它。
因此,您必须自己进行模拟,并且您希望测试的代码使用某种形式的依赖注入来获取对aidl接口的引用非常重要,因此您可以在测试中传递自己的模拟。
如果您想为服务编写单元测试,那么您可以使用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.