MockContentResolver in a ServiceTestCase null poin

2019-05-06 18:30发布

问题:

I'm trying to create a Service in a TDD-ish manner and to that end I have created the following test. The service basically polls a Web Service and puts new information into a Content Provider. Since it is a service, I am using the Content Provider that it will be storing information into as the oracle of the test.

I think what I want to do is create a MockContentResolver in order to achieve this but there is a lack of examples of it outside of a ProviderTestCase2 class. When I run this script however it it null pointers on the addProvider line.

Does anyone have an example of creating/accessing a mocked out content resolver? In a 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);
  }
}

回答1:

To me it seems like you have never instantiated your mContentResolver (you don't have a line like mContentResolver = new MockContentResolver();.