android - 为什么在扩展 AndroidTestCase 的测试类中,getContext() 是否返回 null?

标签 android testing sqliteopenhelper

我有自己的 SQLiteOpenHelper 如下:

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

还有我的 AndroidTestCase 测试类:

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

然后当我执行这个测试类时,我得到了这个错误堆栈跟踪:

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

为什么 getContext() 返回空上下文?因为我在非 Activity 测试用例中?

我是否应该在关于使用 SQLiteOpenHelper 的 Activity 的 ActivityUnitTestCase 中测试我的 SQLiteOpenHelper?

有人可以帮忙吗?我只想测试我的 SQLiteOpenHelper 以确保数据库创建良好。

最佳答案

要访问上下文,您可以:

  1. InstrumentationTestCase 扩展然后调用 getInstrumentation().getContext()
  2. 使用反射访问私有(private)成员

您可以在 this answer 查看代码示例

关于android - 为什么在扩展 AndroidTestCase 的测试类中,getContext() 是否返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16762833/

相关文章:

android - 使用 MainActivity 动态壁纸

android - 如何描述在EditText中设置为editorExtras属性的xml

android - 尝试使用 getExternalStorageDir() 函数在用户 android 设备上存储 PDF 文件

unit-testing - 关于与其他方法组合的stubbing方法的问题

android - 无法在索引处绑定(bind)参数,因为索引超出范围

android - 从 SQLite 数据库中删除需要很长时间,导致挂起

android - System.TypeLoadException : Parent class vtable failed to initialize, 由于 : VTable setup of type AndroidX. SwipeRefreshLayout.Widget.SwipeRefreshLayout

java - 需要关于用于学术研究的 Java 开源项目的推荐

testing - 在 TFS 2012 中订购测试

java - SQLite 连接对象泄露 - Android