title: How do I use MockContentResolver when testing an Android Activity using Espresso?
body: <p>I am using Espresso to test an <code>Activity</code> that displays data retrieved using a <code>ContentProvider</code>.</p>
  
  <p>I'd like to mock the content provider using <a href="https://developer.android.com/reference/android/test/mock/MockContentProvider.html" rel="nofollow noreferrer">MockContentProvider</a> and <a href="https://developer.android.com/reference/android/test/mock/MockContentResolver.html" rel="nofollow noreferrer">MockContentResolver</a>, but I don't know how to make the activity method <code>getContentResolver()</code> return a mock resolver.</p>
  
  <p>(I could insert the data before executing the test, but I'd like to know if it is possible to use a mock provider instead)</p>
  
  <p>UPDATE:
  I still could not make it work, so I'm including some code to try to make it clearer.</p>
  
  <p>MyActivity.java</p>
  
  <pre><code>MyActivity extends AppCompatActivity {
  
      ...
  
      private delete(String id) {
         // The method getContentResolver() is what I want to mock when testing
         getContentResolver().delete(
             Contract.Item.makeUriForItem(id), null, null);
      }
  
      ...
  
  }
  </code></pre>
  
  <p>MyActivityTests.java</p>
  
  <pre><code>@RunWith(AndroidJUnit4.class)
  @LargeTest
  public class StockChartDetailsActivityTests {
  
      @Rule
      public ActivityTestRule&lt;MyActivity&gt; myActivityTestRule = new ActivityTestRule&lt;MyActivity&gt;(
          MainActivity.class);
  
      @Test
      public void test() {
  
      }
  
  }
  </code></pre>
  
  <p>I could not make the suggestion to use Dagger2 to work because <code>getContentResolver()</code> is implemented by android and I can't use <code>@Inject</code> to inject my own <code>ContentResolver</code>.</p>
  
  <p>I could use different strategies:</p>
  
  <ul>
  <li>inserting data in the database before testing. </li>
  <li>have another layer, like a business logic layer, and move calls to <code>getContentResolver()</code> to the classes in this layer and then I could inject (and mock) the business logic classes.</li>
  </ul>
  
  <p>But before using any of these strategies I'd like to know if it is possible to use <code>MockContentResolver</code>.</p>