访问SQLite数据库以进行Android测试

时间:2015-06-22 01:49:26

标签: android sqlite testing android-context

我试图为Android应用程序设置一些单元测试,并且很难访问我的数据库。我在第一次使用时将数据库从assets目录复制到系统。数据库设置如下:

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

我使用单身人士来访问它:

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

现在我尝试在AndroidTestCase中访问它

public class DatabaseTest extends AndroidTestCase {
Database database;

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

}
}

我也尝试使用ServiceTestCase和ApplicationTestCase进行相同的设置,但我总是得到一个' null'因此在创建/打开我的数据库时导致NPE。我现在试了几个小时,似乎完全卡住了。我真的不知道我在这里失踪了什么,有人可以对我有所了解吗?

我使用的数据库实际上是只读的,因此我不需要为单元测试安装单独的数据库。我'

1 个答案:

答案 0 :(得分:0)

您需要使用RenamingDelegatingContext才能获得可用于打开数据库的上下文。

将RenamingDelegatingContext添加到setUp()函数,如下所示:

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

请勿忘记致电database.close();以关闭tearDown()功能中的数据库。

参考:This project on GitHub