我正在尝试以 TDD-ish 方式创建服务,为此我创建了以下测试。该服务基本上轮询 Web 服务并将新信息放入内容提供者。由于它是一项服务,因此我使用内容提供程序将信息存储到其中作为测试的预言机。
我想我想做的是创建一个 MockContentResolver 来实现这一点,但是在 ProviderTestCase2 类之外缺少它的示例。但是,当我运行此脚本时,它在 addProvider 行上指向空指针。
有没有人有创建/访问模拟内容解析器的示例?在 ServiceTestCase 中?
public class OnDemandPollingServiceTests extends ServiceTestCase<OnDemandJobFetchingService> {
private MockContentResolver mContentResolver;
public OnDemandPollingServiceTests() {
super(OnDemandJobFetchingService.class);
}
protected void setUp() throws Exception {
super.setUp();
mContext = getContext();
ContentProvider cp = new OnDemandJobInfoProvider();
mContentResolver.addProvider(OnDemandJobInfoProvider.AUTHORITY, cp);
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testJobInsertion() {
Uri url = Jobs.JobsColumns.CONTENT_URI;
Cursor cursor;
cursor = mContentResolver.query(url, null, null, null, null);
int before = cursor.getCount();
cursor.close();
Intent startIntent = new Intent();
startIntent.setClass(mContext, OnDemandJobFetchingService.class);
startService(startIntent);
cursor = mContentResolver.query(url, null, null, null, null);
int after = cursor.getCount();
cursor.close();
assertTrue(before != after);
}
}
最佳答案
对我来说,您似乎从未实例化 mContentResolver
(您没有像 mContentResolver = new MockContentResolver();
这样的行。