Search code examples
androidtestingsqliteopenhelper

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


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.


Solution

  • 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