I'm trying to test a ContentProvider class, and can't make it work.
getProvider() keeps returning null, but as I understand from the ProviderTestCase2.setUp() code, it shouldn't.
public class NotesProviderTest extends ProviderTestCase2<NotesProvider>
{
...
public NotesProviderTest()
{
super(NotesProvider.class, Contract.AUTHORITY);
}
@Override
protected void setUp() throws Exception
{
super.setUp();
}
public void testNoteProvider__inserts_a_valid_record() throws Exception
{
Note note = new Note(new JSONObject(simpleNoteJson));
NotesProvider provider = getProvider();
Uri insert = provider.insert(Note.URI, note.getContentValues());
assertEquals(1L, ContentUris.parseId(insert));
Cursor cursor = provider.query(Note.URI, null, null, new String[]{}, null);
assertNotNull(cursor);
cursor.close();
}
}
Side note: the provider works if used within the app.
Thanks in advance.
I just ran into this issue myself. You need to tell AndroidJUnit4 to run the setUp method with the @Before annotation. If you don't do this the setUp method will not be called before your unit test runs.
The code snippet for overriding the setUp method on http://developer.android.com/training/testing/integration-testing/content-provider-testing.html is misleading and doesn't mention that you need an @Before annotation.
Try the following:
@Before
@Override
public void setUp() throws Exception
{
setContext(InstrumentationRegistry.getTargetContext());
super.setUp();
}
As part of the setUp() method a MockContentResolver should be created. Use this to create and inject the provider.
See class MockContentResolver: http://developer.android.com/reference/android/test/mock/MockContentProvider.html
Source of example: http://alvinalexander.com/java/jwarehouse/android/test-runner/src/android/test/ProviderTestCase2.java.shtml
Partial sample from example in link above:
@Override
protected void setUp() throws Exception {
super.setUp();
mResolver = new MockContentResolver();
final String filenamePrefix = "test.";
RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
new MockContext2(), // The context that most methods are delegated to
getContext(), // The context that file methods are delegated to
filenamePrefix);
mProviderContext = new IsolatedContext(mResolver, targetContextWrapper);
mProvider = mProviderClass.newInstance();
mProvider.attachInfo(mProviderContext, null);
assertNotNull(mProvider);
mResolver.addProvider(mProviderAuthority, getProvider());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With