问题描述
我有自己的 SQLiteOpenHelper 如下:
I have my own SQLiteOpenHelper as follow :
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 测试类:
And my AndroidTestCase test class :
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();
}
然后当我执行这个测试类时,我得到了这个错误堆栈跟踪:
Then when I execute this test class, i've got this error stack trace :
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()
返回空上下文?因为我在一个非活动测试用例中?
Why does getContext()
returns a null context ? Because I'm in a non Activity test case ?
我应该在关于使用 SQLiteOpenHelper 的活动的 ActivityUnitTestCase
中测试我的 SQLiteOpenHelper 吗?
Should I test my SQLiteOpenHelper in an ActivityUnitTestCase
about an activity that uses the SQLiteOpenHelper ?
有人可以帮忙吗?我只想测试我的 SQLiteOpenHelper 以确保数据库创建良好.
Someone can give some help please ? I just want to test my SQLiteOpenHelper to be sure the database is well created.
推荐答案
要访问 context
,您可以:
- 从 InstrumentationTestCase 扩展,然后调用
getInstrumentation().getContext()
- 使用反射访问私有成员
您可以在这个答案中查看代码示例
这篇关于为什么在扩展 AndroidTestCase 的测试类中,getContext() 是否返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!