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

1

3

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.

Cleopatracleopatre answered 26/5, 2013 at 19:19 Comment(0)
A
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

Aa answered 26/5, 2013 at 20:1 Comment(1)
Thank's for your help. I used the first possibility and I had the same error. And i figured out my mistake, i was using getContext() in the constructor of my test class. Therefore now i can use my AndroidTestCase parent class as I wish.Cleopatracleopatre

© 2022 - 2024 — McMap. All rights reserved.