user1334616
user1334616

Reputation:

Context null when testing SQLiteOpenHelper class

I've found a lot of similar questions, but none that exactly answer my question. What's the best way to unit test a SQLliteOpenHelper class in android?

My error:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean
android.content.Context.deleteDatabase(java.lang.String)' on a null object reference
at android.test.RenamingDelegatingContext.openOrCreateDatabase(RenamingDelegatingContext.java:157)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at  android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at uk.co.ticking_clock.reptilekeeper.data.AnimalOperationsTest.pet_defaultEntries(AnimalOperationsTest.java:36)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)

Code:

@RunWith(AndroidJUnit4.class)
public class DatabaseOperationsTest extends AndroidTestCase {
private MyDbHelper testDb;

@Before
public void setUp() throws Exception {
    super.setUp();
    RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_");
    testDb = MyDbHelper.getInstance(context);
}

@After
public void tearDown() {
    testDb = null;
}

@Test
public void pet_defaultEntries() {
    SQLiteDatabase db = testDb.getWritableDatabase();
    Cursor textDb = db.rawQuery("SELECT name FROM tableOne", null);

    int expected = 2;
    int actual = textDb.getCount();

    Assert.assertTrue(expected  == actual);

}
}

Upvotes: 0

Views: 492

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006869

getContext() would appear to be returning null. As I noted in a comment, AndroidTestCase may not work with @RunWith(AndroidJUnit4.class) and has been deprecated in any case. Use InstrumentationRegistry.getTargetContext() to get at a Context for the application or library code that is being tested.

Upvotes: 3

Related Questions