49

我有一个与远程android服务交互的小应用程序。我想在单元测试中模拟该服务。我使用Robolectric以及JUnit其他测试用例和阴影,但我不知道如何处理远程服务。

使用与真实服务相同的包创建和启动测试服务并使用相同的导出方法是否足够aidl

由于我没有该服务的代码,我假设我不能使用需要实际类RobolectricShadowService 。

非常感谢。

4

2 回答 2

2

我会使用Mockito创建接口的 Mock,然后在测试中将该实例传递给您的代码。您还可以在测试代码中手动创建该接口的实现并使用它。

所以你必须自己做模拟,重要的是你想要测试的代码使用某种形式的依赖注入来获取对aidl接口的引用,这样你就可以在你的测试中传递你自己的模拟。

于 2015-12-29T07:57:39.517 回答
2

如果您想为服务编写单元测试,那么您可以使用 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);
    }
}
于 2018-01-09T10:00:06.197 回答