mDb.delete(DATABASE_TABLE_NAME, null, null);
This is really a solution / way to work ...
I changed the first line in my setUp (..) method to this:
cleanUpDatabase(tableList);
And then I added the cleanUpDatabse (..) method liek this:
private void cleanUpDatabase(List<String> dbTables) { Log.i(LOG_TAG, "Preparing to clean up database..."); DatabaseHelper dbHelper = new DatabaseHelper(getInstrumentation().getTargetContext()); ConnectionSource cs = dbHelper.getConnectionSource(); SQLiteDatabase db = dbHelper.getWritableDatabase(); Log.i(LOG_TAG, "Dropping all tables"); for (String table : dbTables) { db.execSQL("DROP TABLE IF EXISTS " + table); } Log.i(LOG_TAG, "Executing the onCreate(..)"); dbHelper.onCreate(db, cs); Log.i(LOG_TAG, "Verifying the data..."); for (String table : dbTables) { Cursor c = db.query(table, new String[]{"id"}, null, null, null, null, null); int count = c.getCount(); if (count != 1 && (table.equals("project") || table.equals("task"))) { dbHelper.close(); Log.e(LOG_TAG, "We should have 1 record for table " + table + " after cleanup but we found " + count + " record(s)"); throw new RuntimeException("Error during cleanup of DB, exactly one record should be present for table " + table + " but we found " + count + " record(s)"); } else if (count != 0 && !(table.equals("project") || table.equals("task"))) { dbHelper.close(); Log.e(LOG_TAG, "We should have 0 records for table " + table + " after cleanup but we found " + count + " record(s)"); throw new RuntimeException("Error during cleanup of DB, no records should be present for table " + table + " but we found " + count + " record(s)"); } } Log.i(LOG_TAG, "The database has been cleaned!"); dbHelper.close(); }
This piece of code runs before each test, which makes all my tests independent of each other.
Note: in order to get a link to your DatabaseHelper (your own implementation is off-course;)), you cannot call getActivity() , because it will start your activity (and, therefore, will do all your initial DB loading (if any ..)
source share