Skip to content Skip to sidebar Skip to footer

Testing Sqliteopenhelper Subclass With Junit

I am writing JUnit tests for my Android app. I have read through the Android developer resources (testing fundamentals, Spinner example test, etc.). Now I want to test my SQLiteOpe

Solution 1:

I was looking for an answer to exactly this problem, and found this link as well as another interesting related question here:

The accepted answer by @Pietro shows some simple code, using a basic AndroidTestCase, which will help directly to answer the question.

publicclassDatabaseTestextendsAndroidTestCase {
    private MyDatabase db;

    publicvoidsetUp(){
        RenamingDelegatingContextcontext=newRenamingDelegatingContext(getContext(), "test_");
        db = newMyDatabase(context);
    }

    publicvoidtestAddEntry(){
        // Here I have my new database which is not connected to the standard database of the App
    }

    publicvoidtearDown()throws Exception{
        db.close(); 
        super.tearDown();
    }
}

I was happy at how simple it looks. In my case I'm new to Android testing, so even the simple stuff seems difficult at the moment.


But the interesting part which is key, is using the RenamingDelegatingContext class as your "context" instead of just using a normal context. This seems to build on the comments made by @Jens.

This class wraps a given context and delegates most operations to that context. The useful part is that it performs database and file operations with a renamed database/file name (see documentation online).

This allows your TEST code to use an actual different instance of the database to your PRODUCTION code - at least in my case this is going to be useful.


Here is another related post where the accepted answer says pretty much the same thing:

Some useful tips in there about using ContentProvider instead (but that's a different issue for another day).

Solution 2:

following link talk about testing in android:

http://developer.android.com/tools/testing/testing_android.html

may be you have already seen it just posting it in case you have missed going through it.. it is a very good resource to learn about junit in android...

Solution 3:

For testing with Android Studio,

You should use MockContext instead of RenamingDelegatingContext.

If you use RenamingDelegatingContext, You would get context as null. For AndroidTestCase, getContext() would return null. And for InstrumentationTestCase, getInstrumentation().getContext() would return null.

For further information, see this answer. https://stackoverflow.com/a/29063736/1020456

Post a Comment for "Testing Sqliteopenhelper Subclass With Junit"