繁体   English   中英

如何从 Android 仪器测试中的测试资产访问 File 对象?

[英]How to access File object from test assets in Android instrumentation tests?

我想在 Android 仪器测试中以某种方式读取File对象。

我正在尝试使用位于androidTest assets文件夹来获取它

File("//android_asset/myFile.jpg")

不幸的是我无法得到这个文件。 有人知道如何创建这样的File对象吗? 它不一定必须位于assets

如果您需要复制设备中的文件,例如测试需要文件路径而不是流的 C++ 库,您可以通过这种方式手动复制:

    @Test
    public void checkFileWorkingTxt() throws IOException {
        String path = "filepath.txt";
        Context context = InstrumentationRegistry.getTargetContext();

        // Creation of local file.
        InputStream inputStream = context.getResources().getAssets().open(path);

        // Copy file to device root folder
        File f = new File(context.getExternalCacheDir() + path);
        FileOutputStream outputStream = new FileOutputStream(f);
        FileUtils.copy(inputStream, outputStream);

        // Check that everything works with native function
        bool result = NativeLibrary.check_txt(f.getAbsolutePath());
        assertTrue(result);
    }

这可能不是最好的方法,但它有效。

假设您在src/androidTest/assets/myasset.txt下有一个文件,您可以像InstrumentationRegistry.getContext().getResources().getAssets().open("myasset.txt");一样访问它InstrumentationRegistry.getContext().getResources().getAssets().open("myasset.txt");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM