代码之家  ›  专栏  ›  技术社区  ›  Jeff Axelrod

如何将数据库测试夹具从单元测试应用程序传输到设备

  •  5
  • Jeff Axelrod  · 技术社区  · 15 年前

    我正在编写一个androidjunit测试,想要复制/重置一个测试夹具文件(它是一个SQLite数据库文件)。如果我在主应用程序中,我知道我可以将该文件放在assets目录中并使用它 getResources().getAssets().open(sourceFile)

    但是,此API似乎无法从 ActivityInstrumentationTestCase2 班级。

    有没有一种简单的方法从测试PC上复制一个文件,或者我应该在设备上保留一个测试夹具的新副本,然后在一个临时文件上复制它?

    2 回复  |  直到 13 年前
        1
  •  6
  •   Alex Pretzlav    15 年前

    测试应用程序和主应用程序中的资源可以在检测测试用例中分别访问。如果要访问测试项目本身的res/raw或assets文件夹中的资源,可以使用

    getInstrumentation().getContext().getResources()
    

    getInstrumentation().getTargetContext().getResources()
    

    但是请注意,您永远不能修改assets文件夹中的文件;

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

    如果您要做的是修改您正在测试的活动所使用的文件的路径,那么您应该使用 ActivityUnitTestCase setActivityContext() 用一个 RenamingDelegatingContext more complex constructor 为大多数操作包装目标上下文,但将测试应用程序的上下文用于文件操作,因此活动将访问存储在测试应用程序中的文件,而不是主应用程序,但仍使用主应用程序中的其他资源。

        2
  •  3
  •   Jeff Axelrod    15 年前

    为了实现这一点,我所做的工作(不是很优雅)是将测试夹具复制到我的设备(或模拟设备)上cleantestdatabase.db数据库“然后在测试代码中,我将它复制到”测试数据库.db,“这样我就可以用我的测试来修改它,但是可以将它重置为一个已知的状态。代码如下:

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