5

I have an Android app with a database with version 1.

I added a data column in one table and idi a migration into a new release.

The problem I have is how to do unit tests for this. I needed to check if old data are correct inserted in the new structure and the new column is added and filled in the right way.

How would I best do this? Thanks in advance.

IrApp
  • 1,823
  • 5
  • 24
  • 42

2 Answers2

2

You can create a test case that builds an old version of your database and then run your migration. Here is a stripped down example.

public class DbHelperTest extends AndroidTestCase {
private SQLiteDatabase db;

@Override
public void setUp() throws Exception {
    super.setUp();
    mContext = new RenamingDelegatingContext(getContext(), "db_helper_test_");
    SQLiteDatabase.CursorFactory cursorFactory = new SQLiteDatabase.CursorFactory() {

        @Override
        public Cursor newCursor(final SQLiteDatabase db, final SQLiteCursorDriver masterQuery, final String editTable,
                                final SQLiteQuery query) {
            return new SQLiteCursor(db, masterQuery, editTable, query);
        }
    };
    db = SQLiteDatabase.create(cursorFactory);

    createV14Db(db);
}

@Override
public void tearDown() throws Exception {
    super.tearDown();
    db.close();
}

private void createV14Db(SQLiteDatabase db) {
    // Create tables and indices
    db.execSQL(...);

    // Create some data
    db.execSQL(...);
}

public void testDbUpgrade() {
    DbHelper dbHelper = new DbHelper(mContext);
    dbHelper.onUpgrade(db, 14, 100);

    // Check that things have been upgraded correctly
}
}
Tad
  • 4,668
  • 34
  • 35
0

You have to test 2 scenarios :

  1. User installs new version directly.
  2. User is on an older version and upgrades to new version.

Testing the 2nd scenario is generally tricky.

What I generally do to test scenario 2 is :

  1. Un-install the app from mobile.
  2. I switch to code version of release 1 - Note that I use GIT and hence it is very easy to switch to older versions.
  3. Run the app on device using Android studio.
  4. Create some test data.
  5. Switch to release 2 of code.
  6. Start debugging in Android studio. At this point have break points in your DB upgrade methods to ensure that DB upgrade is smooth.
  7. Continue with the rest of the testing.
Varun Verma
  • 542
  • 4
  • 17