Accesing SQLite database for Android testing

624 views Asked by At

I'm trying to set up some Unit testing for an android application and having a hard time getting access to my database. I copy the database from the assets directory to the system during first usage. Database is set up as following:

private class DBOpenHelper extends SQLiteOpenHelper {
    private Context context;

    public DBOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, 2);
        this.context = context;

        // Write a full path to the databases of your application
        openDataBase();
    }

    // This piece of code will create a database if it’s not yet created
    public void createDataBase() {
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e(this.getClass().toString(), "Copying error");
                throw new Error("Error copying database!");
            }
        } else {
            Log.d("DB", "Delete");

            Log.i(this.getClass().toString(), "Database already exists");
        }
    }

    // Performing a database existence check
    private boolean checkDataBase() {
        SQLiteDatabase checkDb = null;
        try {
            String path = DB_PATH + DATABASE_NAME;
            checkDb = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLException e) {
            Log.e(this.getClass().toString(), "Error while checking db");
        }
        // Android doesn’t like resource leaks, everything should
        // be closed
        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null;
    }

    // Method for copying the database
    private void copyDataBase() throws IOException {
        // Open a stream for reading from our ready-made database
        // The stream source is located in the assets
        InputStream externalDbStream = context.getAssets().open(
                    DATABASE_NAME);

        // Path to the created empty database on your Android device
        String outFileName = DB_PATH + DATABASE_NAME;

        // Now create a stream for writing the database byte by byte
        OutputStream localDbStream = new FileOutputStream(outFileName);

        // Copying the database
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = externalDbStream.read(buffer)) > 0) {
            localDbStream.write(buffer, 0, bytesRead);
        }
        // Don’t forget to close the streams
        localDbStream.close();
        externalDbStream.close();
    }

    public SQLiteDatabase openDataBase() throws SQLException {
        String path = DB_PATH + DATABASE_NAME;

        if (database == null) {
            createDataBase();
            database = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READONLY);
        }
        Log.d("DB", "Open");

        return database;
    }

    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
        }
        Log.d("DB", "Close");

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("DB", "Create");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("DB", "Update");
    }

I use a singleton to access it:

private static Database sInstance;

/**
 * Open the database
 *
 * @param context The applications context
 */
public Database(Context context) {
    DBOpenHelper openHelper = new DBOpenHelper(context);
    database = openHelper.openDataBase();
}

public static synchronized Database getDatabase(
        Context context) {
    if (sInstance == null) {
        sInstance = new Database(context);
    }
    return sInstance;
}

Now I try to access it in my AndroidTestCase

public class DatabaseTest extends AndroidTestCase {
Database database;

@Override
public void setUp() throws Exception {
    super.setUp();
    database = Database.getDatabase(getContext());

}
}

I've also tried the same setup using ServiceTestCase and ApplicationTestCase, but I always get a 'null' context thus resulting in a NPE upon creating/opening my database. I'm trying this for several hours now, and seem to be completely stuck. I really don't know what I'm missing here, can anybody shed some light on me?

The database I'm using is actually read-only, so I don't need to install a separate one for the unit testing. I'

1

There are 1 answers

3
BrentM On

You need to use a RenamingDelegatingContext in order to get a context you can use to open your database.

Add a RenamingDelegatingContext to your setUp() function as follows:

public class DatabaseTest extends AndroidTestCase {
Database database;

@Override
public void setUp() throws Exception {
    super.setUp();
    RenamingDelegatingContext context
            = new RenamingDelegatingContext(getContext(), "test_");

    database = Database.getDatabase(context);
  }
}

Don't forget to call database.close(); to close your database in the tearDown() function.

Reference: This project on GitHub.