im using espresso to clear database in my app Im setting activity like this
@Rule
@JvmField
val activity = ActivityTestRule<PhotoPrinterActivity>(PhotoPrinterActivity::class.java,false,false)
And this is my before function
@Before
open fun setup() {
clearDatabase()
activity.launchActivity(null)
// Waiting for start app success fully
}
And this is my clear database code
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)
}
}
}
Issue is when clear database success and perform add some data into 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)
Anyone please help me !Thanks so much!
Use @BeforeClass and InstrumentationRegistry in your espresso tests to delete database:
@BeforeClass
public static void beforeClass() {
InstrumentationRegistry.getTargetContext().deleteDatabase("database_name");
}
And to prevent bugs when executing multiple espresso tests at once, use Android Test Orchestrator. It will execute all of them separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With