在测试用例浓缩咖啡之前清除数据库

Phạ*_*Nam 4 android ui-automation kotlin android-espresso

即时通讯使用意式浓缩咖啡清除我应用程序中的数据库即时通讯设置活动是这样的

@Rule
    @JvmField
    val activity = ActivityTestRule<PhotoPrinterActivity>(PhotoPrinterActivity::class.java,false,false)
Run Code Online (Sandbox Code Playgroud)

这是我之前的功能

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

    }
Run Code Online (Sandbox Code Playgroud)

这是我清晰的数据库代码

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

    }
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

任何人都请帮助我!非常感谢!

ste*_*edi 6

在您的浓缩咖啡测试中使用@BeforeClassInstrumentationRegistry删除数据库:

@BeforeClass
public static void beforeClass() {
    InstrumentationRegistry.getTargetContext().deleteDatabase("database_name");
}
Run Code Online (Sandbox Code Playgroud)

为了防止在一次执行多个espresso测试时出现错误,请使用Android Test Orchestrator。它将单独执行所有它们。