不要使用robolectric重新创建数据库

时间:2014-01-30 13:59:53

标签: android sqlite android-sqlite robolectric android-testing

我知道Robolectric没有使用它在内存数据库中使用的真正的SQLite数据库。但每次调用getWritableDatabase()getWritableDatabase()时都会重新创建数据库。

有没有办法让Robolectric重新创建数据库让我们说只有在调用setUp()时才这样?

1 个答案:

答案 0 :(得分:0)

我从github下载了Robolectric源代码并在这个问题的答案中解释了这些更改:

Testing SQLite database in Robolectric

ShadowSQLiteOpenHelper课程中,我做了以下更改:

  • 定义此字段:

    private static Context previousContext;
    
  • 在构造函数中添加了这个:

    if (previousContext == null) {
        previousContext = context;
    } else {
        if(previousContext == context) {
            return;
        } else {
            previousContext = context;
        }
    }
    
  • 更改了getDatabase()方法,如下所示:

    private SQLiteDatabase getDatabase() {
        if (database == null) {
            database = SQLiteDatabase.openDatabase("path", null, 0);
            realHelper.onCreate(database);
        }
    
        realHelper.onOpen(database);
        return database;
    }
    

现在一切都很完美。