2

ProviderTestCase2<>を拡張するテストクラスがあります。

このテストクラスデータベースにいくつかの.dbファイルのデータを入力したいと思います。

.dbファイルをProviderTestCase2のモックコンテキストにプッシュする特定の方法はありますか?

それ以外の場合は、.dbファイルからデータベースにデータを入力する方が簡単です。

どうもありがとうございます!!

4

1 に答える 1

0

SD カードなどから既存の .db ファイルをコピーするのはどうですか? これは、これを実現する簡単なコードです。

private void importDBFile(File importDB) {
    String dataDir = Environment.getDataDirectory().getPath();
    String packageName = getPackageName();

    File importDir = new File(dataDir + "/data/" + packageName + "/databases/");
    if (!importDir.exists()) {
        Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
        return;
    }

    File importFile = new File(importDir.getPath() + "/" + importDB.getName());

    try {
        importFile.createNewFile();
        copyDB(importDB, importFile);
        Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show();
    } catch (IOException ex) {
        Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
    }
}

private void copyDB(File from, File to) throws IOException {
    FileChannel inChannel = new FileInputStream(from).getChannel();
    FileChannel outChannel = new FileOutputStream(to).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

うまくいけば、これはあなたのシナリオでうまくいくでしょう

于 2011-08-04T06:41:14.377 に答える