blue_diamond blue_diamond - 3 months ago 15x
Android Question

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

public void onCreate(SQLiteDatabase sqLiteDatabase) {
/* My create code */

public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
/* My upgrade code */

public void onOpen(SQLiteDatabase db) {

And my AndroidTestCase test class :

public class MyOpenHelperTest extends AndroidTestCase {

protected MyOpenHelper myOpenHelper;
protected SQLiteDatabase sqLiteDatabase;

public MyBdOpenHelperTest() {

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>(
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(
at junit.runner.BaseTestRunner.getTest(

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

Should I test my SQLiteOpenHelper in an
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.


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