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.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
blue_diamond
  • 65
  • 3
  • 8

1 Answers1

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

Community
  • 1
  • 1
Sean
  • 5,176
  • 2
  • 34
  • 50
  • 3
    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. – blue_diamond May 26 '13 at 21:00