How to transfer a database test fixture to a device from unit test application

I am writing an Android JUnit test and want to copy / reset the file of the test file (this is the SQLite database file.) If I were in the main application, I know that I can just put the file into assets and use getResources().getAssets().open(sourceFile)

However, this API is not accessible from the class ActivityInstrumentationTestCase2.

Is there an easy way to copy a file from a testing PC or just save a new copy of the test device on the device and copy it to a temporary file?

Thank!

+5
source share
2 answers

( ), ( ). "cleantestdatabase.db". "testdatabase.db", , reset . :

copyFile("cleantestdatabase.db", "testdatabase.db");

private void copyFile(String source, String dest) throws IOException{
    String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + getActivity().getString(R.string.default_dir);
    File newDir = new File(rootPath);
    boolean result = newDir.mkdir();
    if(result == false){
        Log.e("Error", "result false");
    }

    InputStream in = new FileInputStream(rootPath + source);    
    File outFile = new File(rootPath + dest);
    if(outFile.exists()) {
        outFile.delete();
    }
    outFile.createNewFile();

    OutputStream out = new FileOutputStream(outFile);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}
+3

. , res/raw assets ,

getInstrumentation().getContext().getResources()

( "" ),

getInstrumentation().getTargetContext().getResources()

, , ,

getResources().getAssets().open(sourceFile)

InputStream. . , APK .

, , ActivityUnitTestCase setActivityContext() RenamingDelegatingContext. , . , , , , , , .

+6

All Articles