How to execute JUnit test ContentResolver.notifyChange

I am writing tests for ContentProvider , in insert I am reporting changes with getContext().getContentResolver().notifyChange(mUri, null);

my test class extends ProviderTestCase2 . I created the following layout of the ContentObserver class:

 private class ContentObserverMock extends ContentObserver { public boolean changed = false; public ContentObserverMock(Handler handler) { super(handler); // TODO Auto-generated constructor stub } @Override public void onChange(boolean selfChange) { changed = true; } @Override public boolean deliverSelfNotifications() { return true; } } 

and this is a test example:

 public void testInsertNotifyContentChanges() { ContentResolver resolver = mContext.getContentResolver(); ContentObserverMock co = new ContentObserverMock(null); resolver.registerContentObserver(CONTENT_URI, true, co); ContentValues values = new ContentValues(); values.put(COLUMN_TAG_ID, 1); values.put(COLUMN_TAG_CONTENT, "TEST"); resolver.insert(CONTENT_URI, values); assertTrue(co.changed); } 

it looks like onChange never called, I also tried ContentObserverMock co = new ContentObserverMock(new Handler()); with the same result.

what am i doing wrong here?

+8
android android-contentresolver android-testing
source share
2 answers

ProviderTestCase2 uses a MockContentResolver . Checking the source code, the notifyChange method notifyChange nothing.

 @Override public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) { } 

Your scenerio cannot be tested with ProviderTestCase2 . Take a look at ProviderTestCase3 , but it uses private android packages.

Edit: I created a library consisting of the new ProviderTestCase3 class as a replacement for ProviderTestCase2 , which calls ContentResolver.notifyChanged calls for internal observers registered with ProviderTestCase3.registerContentObserver . You can use it to check for change notifications. https://github.com/biegleux/TestsUtils

Using:

 public void testInsertNotifyContentChanges() { ContentObserverMock observer = new ContentObserverMock(new Handler()); registerContentObserver(CONTENT_URI, true, observer); ContentValues values = new ContentValues(); values.put(COLUMN_TAG_ID, 1); values.put(COLUMN_TAG_CONTENT, "TEST"); getMockContentResolver().insert(CONTENT_URI, values); assertTrue(observer.mChanged); } 

Don't forget extends ProviderTestCase3<YourProvider> .

+4
source share

I use Robolectric to disable as far as I can without running the emulator. I confirmed that you are calling the update in contentResolver as follows:

 ShadowContentResolver contentResolver = Robolectric.shadowOf( service.getContentResolver()); final List<NotifiedUri> notifiedUris = contentResolver.getNotifiedUris(); assertThat(notifiedUris.get(0).uri, is(uriToVerify)); 
+4
source share

All Articles