Android单元测试 - SQLiteReadOnlyDatabaseException:尝试编写只读数据库(代码1032)

时间:2016-10-29 18:24:04

标签: android sqlite android-sqlite

我刚刚为我的CRUD实现创建了单元测试,我有这个奇怪的问题。当测试一个接一个地运行时,它们都会通过。但是当我想运行整个套件时,它们会因错误而失败

android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insertOrThrow(SQLiteDatabase.java:1367)
at cz.pikadorama.simpleorm.DatabaseSanityTest.testDelete(DatabaseSanityTest.java:55)

这是代码

@Before
public void prepareDatabase() throws InstantiationException, IllegalAccessException {
    Context context = InstrumentationRegistry.getTargetContext();
    context.deleteDatabase(DATABASE_NAME);
    DbManager.registerHelper(new TestSQLiteHelper(context), new Class<?>[]{TestEntity.class});
}

@Test
public void testDelete() {
    Dao<TestEntity> dao = DaoManager.getDao(TestEntity.class);
    TestEntity entity = new TestEntity();
    dao.create(entity);  
    dao.delete(entity);
    assertEquals(0, dao.findAll().size());
}

// other tests for insert, update, ... follow

顺便说一句,DAO实现始终将可写数据库打开为sqliteOpenHelper.getWritableDatabase()

1 个答案:

答案 0 :(得分:1)

这与DbManager和DaoMaster是单例(以及我认为的底层数据库)这一事实有关:@Before中的代码在每次测试之前被调用,这会破坏类中的东西,可能,应该只启动一次。

@Before注释更改为@BeforeClass,以便只执行一次初始化。