【问题标题】:Accesing SQLite database for Android testing访问 SQLite 数据库以进行 Android 测试
【发布时间】:2015-09-07 09:11:45
【问题描述】:

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

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 进行相同的设置,但我总是得到一个“空”上下文,因此在创建/打开我的数据库时会导致 NPE。我现在尝试了几个小时,似乎完全被卡住了。我真的不知道我在这里错过了什么,有人能帮我解释一下吗?

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

【问题讨论】:

    标签: android sqlite testing android-context


    【解决方案1】:

    您需要使用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);
      }
    }
    

    不要忘记在tearDown() 函数中调用database.close(); 来关闭您的数据库。

    参考:This project on GitHub

    【讨论】:

    • 我似乎可以访问可用的上下文,但我的 TestCase 仍然无法访问现有数据库或资产文件夹中的数据库文件。尝试访问资产时,它会再次抛出 NPE。
    • 似乎 RenamingDelegatingContext 只能访问数据库而不能访问应用程序资产资源。我不知道 AndroidTestCase 中的解决方案。
    • 如果它可以访问我的应用程序数据库,我会很好,但它无法打开它,因此尝试从我的资产中复制一个新的。
    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多