我有自己的SQLiteOpenHelper如下:
public class MyOpenHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "dbname";
public MyOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
/* My create code */
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
/* My upgrade code */
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
}
我的AndroidTestCase测试类:
public class MyOpenHelperTest extends AndroidTestCase {
protected MyOpenHelper myOpenHelper;
protected SQLiteDatabase sqLiteDatabase;
public MyBdOpenHelperTest() {
super();
assertNotNull( getContext() );
this.myBdOpenHelper = new MyOpenHelper(getContext());
this.sqLiteDatabase = this.myOpenHelper.getReadableDatabase();
}
然后当我执行这个测试类时,我得到了这个错误堆栈跟踪:
junit.framework.AssertionFailedError: Exception in constructor:
testAndroidTestCaseSetupProperly (junit.framework.AssertionFailedError
at fr.power.db.MyOpenHelperTest.<init>(MyOpenHelperTest.java:21)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at junit.runner.BaseTestRunner.getTest(BaseTestRunner.java:118)
...
为什么getContext()
会返回空上下文?因为我在非活动测试案例中?
我应该在ActivityUnitTestCase
中测试关于使用SQLiteOpenHelper的活动的SQLiteOpenHelper吗?
有人可以帮忙吗?我只是想测试我的SQLiteOpenHelper以确保数据库已经很好地创建。
答案 0 :(得分:1)
要访问context
,您可以:
getInstrumentation().getContext()
您可以在this answer
查看代码示例