I’m writing tests for a ContentProvider, in insert I’m notifying about changes with getContext().getContentResolver().notifyChange(mUri, null);
my tests class extends ProviderTestCase2. I created the following mock 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 the test case:
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);
}
seems like onChange is never called, I also tried ContentObserverMock co = new ContentObserverMock(new Handler()); with the same result.
what am I doing wrong here ?
ProviderTestCase2usesMockContentResolver. Checking source code, it’snotifyChangemethod does nothing.Your scenerio can’t be tested with
ProviderTestCase2. Take a look at ProviderTestCase3, but it uses android private packages.Edit: I have made a library consisting of new
ProviderTestCase3class as a replacement forProviderTestCase2that keeps calls toContentResolver.notifyChangedinternal to observers registered withProviderTestCase3.registerContentObserver. You can use it to test notify changes.https://github.com/biegleux/TestsUtils
Usage:
Don’t forget to
extends ProviderTestCase3<YourProvider>.