为什么在扩展AndroidTestCase,一的getContext测试类()函数返回null? [英] Why in a test class that extends AndroidTestCase, getContext() function returns null?
问题描述
我有我自己的SQLiteOpenHelper如下:
I have a 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 getContext() returns a null context ? Because i'm in a non Activity test case ?
我应该测试我SQLiteOpenHelper在ActivityUnitTestCase有关使用SQLiteOpenHelper活动?
Should i test my SQLiteOpenHelper in 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 database is well created.
推荐答案
有关访问背景
,您可以:
- 从 InstrumentationTestCase 扩展,然后调用
getInstrumentation()的getContext()
- 使用反射来访问私有成员
- Extend from InstrumentationTestCase and then call
getInstrumentation().getContext()
- Use reflection to access a private member
您可以看到code样品<一个href=\"http://stackoverflow.com/questions/8605611/get-context-of-test-project-in-android-junit-test-case\">this回答
You can see code samples at this answer
这篇关于为什么在扩展AndroidTestCase,一的getContext测试类()函数返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!