Testing RoboContentProvider using ProviderTestCase2

114 views
Skip to first unread message

Alex Horsa

unread,
Sep 25, 2014, 11:31:03 AM9/25/14
to robo...@googlegroups.com
Hello,

I'm trying to write some tests for a RoboContentProvider.

public class DatabaseProvider extends RoboContentProvider {

    public static final String TAG = "DatabaseProvider";

    @Inject
    protected BaseDatabaseHelper mDatabaseHelper;

    @Override
    public boolean onCreate() {
        super.onCreate();
        return true;
    }
}

public class TestContentProvider extends ProviderTestCase2<DatabaseProvider> {

    public TestContentProvider() {
        super(DatabaseProvider.class, DatabaseContract.CONTENT_AUTHORITY);
    }

    public void testQueryQuestions() {
        ContentProvider contentProvider = getProvider();
        Cursor cursor = contentProvider.query(DatabaseContract.Question.CONTENT_URI, null, null, null, null);
        assertNotNull(cursor);
    }
}

The output:

java.lang.ClassCastException: android.test.ProviderTestCase2$MockContext2 cannot be cast to android.app.Application
at roboguice.RoboGuice.getInjector(RoboGuice.java:148)
at roboguice.content.RoboContentProvider.onCreate(RoboContentProvider.java:17)
at com.app.providers.DatabaseProvider.onCreate(DatabaseProvider.java:41)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1214)
at android.content.ContentProvider.attachInfoForTesting(ContentProvider.java:1178)
at android.test.ProviderTestCase2.setUp(ProviderTestCase2.java:143)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1738)

From what I understand is that the ProviderTestCase2 doesn't have the Application context. Is it possible to write tests for robo content providers using this class? 


Alex Horsa

unread,
Oct 1, 2014, 6:55:53 AM10/1/14
to robo...@googlegroups.com
I found a workaround which may help others. I am still curious why ProviderTestCase2 doesn't work.

Code inspired from ProviderTestCase2:

public class MyProviderTestCase extends AndroidTestCase {

    MockContentResolver mResolver;
    ContentProvider mProvider;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mResolver = new MockContentResolver();

        mProvider = new DatabaseProvider(); // This can be parameterized
        mProvider.attachInfo(getContext().getApplicationContext(), null);
        assertNotNull(mProvider);
        mResolver.addProvider(DatabaseContract.CONTENT_AUTHORITY, getProvider());
    }

    public ContentProvider getProvider() {
        return mProvider;
    }
Reply all
Reply to author
Forward
0 new messages