I am using Espresso to test an Activity
that displays data retrieved using a ContentProvider
.
I'd like to mock the content provider using MockContentProvider and MockContentResolver, but I don't know how to make the activity method getContentResolver()
return a mock resolver.
(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)
UPDATE: I still could not make it work, so I'm including some code to try to make it clearer.
MyActivity.java
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);
}
...
}
MyActivityTests.java
@RunWith(AndroidJUnit4.class)
@LargeTest
public class StockChartDetailsActivityTests {
@Rule
public ActivityTestRule<MyActivity> myActivityTestRule = new ActivityTestRule<MyActivity>(
MainActivity.class);
@Test
public void test() {
}
}
I could not make the suggestion to use Dagger2 to work because getContentResolver()
is implemented by android and I can't use @Inject
to inject my own ContentResolver
.
I could use different strategies:
- inserting data in the database before testing.
- have another layer, like a business logic layer, and move calls to
getContentResolver()
to the classes in this layer and then I could inject (and mock) the business logic classes.
But before using any of these strategies I'd like to know if it is possible to use MockContentResolver
.