测试SQLiteOpenHelper类时,上下文为null

时间:2016-05-15 14:35:09

标签: android sqlite unit-testing

我发现了很多类似的问题,但没有一个能完全回答我的问题。 什么是在android中单元测试SQLliteOpenHelper类的最佳方法?

我的错误:

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)

代码:

@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);

}
}

1 个答案:

答案 0 :(得分:3)

getContext()似乎正在返回null。正如我在评论中指出的那样,AndroidTestCase可能无法与@RunWith(AndroidJUnit4.class)一起使用,并且在任何情况下都已被弃用。使用InstrumentationRegistry.getTargetContext()获取正在测试的应用程序或库代码的Context