Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio Unit test SQLiteDataBase is null

I'm new to Unit testing and I want to test my SQLiteDataBase.

I have a class named MySQLiteHelper that extends SQLiteOpenHelper. I have a class named LocationDataHandler that I use to add or delete elements from my DataBase. And I have a class LocationDataHandlerTest, that extends AndroidTestCase, to test my LocationDataHandler class.

I'm trying to test my SQLite Database but I seem to be a little bit lost between all the different contexts.

here is my code :

//Context context = new Activity();

//IsolatedContext context = getMockContext();

//Context context = new MockContext();

//Context context = getInstrumentation().getContext();

  Context context = getContext();

  helper = new MySQLiteHelper(context);
  assertNotNull(helper);

  SQLiteDatabase db = helper.getWritableDatabase();
  assertNotNull(db); <---- it fails here !

as you can see I tried with many different contexts that i saw people use and work with. I really don't understand why it doesn't work in my case.

My problem is that the test is failing on the line "assertNotNull(db);" meaning i can never retrieve my dataBase.

Am I doing this the wrong way ? Am I not using the right context ?

Edit : Here is my logcat :

junit.framework.AssertionFailedError
    at junit.framework.Assert.fail(Assert.java:55)
    at junit.framework.Assert.assertTrue(Assert.java:22)
    at junit.framework.Assert.assertNotNull(Assert.java:256)
    at junit.framework.Assert.assertNotNull(Assert.java:248)
    at junit.framework.TestCase.assertNotNull(TestCase.java:417)
    at com.databerries.LocationDataHandlerTest.testAddLocation(LocationDataHandlerTest.java:72)
like image 837
Théo Richard Avatar asked May 28 '15 14:05

Théo Richard


1 Answers

Yes, it is a context issue. All those contexts (including the ones you commented out) are null.

You could create a context:

context = new MockContext();

To the same database (or other resources) as your application, you can use (since you're using AndroidTestCase):

context = getInstrumentation().getContext();

There's a proper way to created and use a RoamingDelegatingContext, but it doesn't appear that you need that for your test.

You may consider reading Android Testing Fundamentals to help understand some issues with testing and the level of access/resources needed.

like image 157
iheanyi Avatar answered Sep 19 '22 19:09

iheanyi