我想对一个使用 Android DownloadManager 服务的类进行单元测试,但我不确定该怎么做。我应该实际使用 DownloadManager 服务还是有什么方法可以模拟它?我宁愿不让我的测试调用外部网络服务器。我可以使用现有的测试库吗?
最佳答案
- 此解决方案使用 Robolectric
需要了解的一件重要事情是,下载管理器请求的计数从 -1 开始。因此,如果您对请求进行排队,请求计数将为 0。
- 模拟您的 DownloadManager 对象
编写测试
public void shouldEnqueueRequest() { //... //... verify(downloadManager, times(1)).enqueue(anyObject()); //Is the DownloadManager empty assertThat(shadowOf(downloadManager).getRequestCount(), greaterThan(-1)); //Get the request from the DownloadManager ShadowRequest realRequest = shadowOf(shadowOf(downloadManager).getRequest(0)); assertThat(realRequest, notNullValue()); assertThat(realRequest.getDescription(), equalTo("Your description")); assertThat(realRequest.getTitle(), equalTo(APP_NAME)); }
关于android - 单元测试和 Android DownloadManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824760/