数据库
首页 > 数据库> > android – 在testcase espresso之前清除数据库

android – 在testcase espresso之前清除数据库

作者:互联网

我使用espresso来清除我的应用程序中的数据库
我设置这样的活动

@Rule
    @JvmField
    val activity = ActivityTestRule<PhotoPrinterActivity>(PhotoPrinterActivity::class.java,false,false)

这是我之前的功能

    @Before
    open fun setup() {
        clearDatabase()
        activity.launchActivity(null)
        // Waiting for start app success fully

    }

这是我清晰的数据库代码

 fun clearDatabase() {
        val databaseList = InstrumentationRegistry.getInstrumentation().targetContext.databaseList()
        for (database in databaseList) {

            // when transaction rollback files exists they are always locked so we can't delete them
            if (database.contains(".db-journal")) {
                InstrumentationRegistry.getTargetContext().deleteDatabase(database)
                continue
            }

            // when using transaction write ahead logging then this db files are listed but often they don't exist
            if (database.contains(".db-wal") || database.contains(".db-shm")) {
                InstrumentationRegistry.getTargetContext().deleteDatabase(database)
                continue
            }
            Log.v("EspressoMacchiato", "deleting " + database)
            var databasePath = InstrumentationRegistry.getInstrumentation().targetContext.getDatabasePath(database)
            if (databasePath.exists()) {
                InstrumentationRegistry.getInstrumentation().targetContext.deleteDatabase(database)
            }
        }

    }

问题是当数据库成功清除并执行将一些数据添加到数据库中时

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:786)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)

有人请帮助我!非常感谢!

解决方法:

在espresso测试中使用@BeforeClassInstrumentationRegistry删除数据库:

@BeforeClass
public static void beforeClass() {
    InstrumentationRegistry.getTargetContext().deleteDatabase("database_name");
}

并且为了防止在一次执行多个espresso测试时出现错误,请使用Android Test Orchestrator.它将分别执行所有这些错误.

标签:android,kotlin,android-espresso,ui-automation
来源: https://codeday.me/bug/20190622/1263064.html