Why in a test class that extends AndroidTestCase, does getContext() return null?

只愿长相守 提交于 2019-12-10 19:28:27

问题


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

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)
...

Why does getContext() returns a null context ? Because I'm in a non Activity test case ?

Should I test my SQLiteOpenHelper in an ActivityUnitTestCase about an activity that uses the SQLiteOpenHelper ?

Someone can give some help please ? I just want to test my SQLiteOpenHelper to be sure the database is well created.


回答1:


For accessing a context you can:

  1. Extend from InstrumentationTestCase and then call getInstrumentation().getContext()
  2. Use reflection to access a private member

You can see code samples at this answer



来源:https://stackoverflow.com/questions/16762833/why-in-a-test-class-that-extends-androidtestcase-does-getcontext-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!