android - 如何从我的 android 测试项目的 Assets 文件夹加载文件?

标签 android android-testing

有没有办法获取 Assets 文件夹中的其中一个文件的文件对象。我知道如何加载此类文件的输入流,但我需要一个文件对象而不是输入流。

这样我加载输入流

    InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");

但是我需要文件对象,这样文件就找不到了

File f = new File("assets/example.stf2");

最佳答案

找到了一个适用于我的情况的解决方案,也许其他人也可以使用它。

从我的 android 测试项目中检索文件到输入流

InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");

在被测android应用的External-Cachedir上创建一个文件

File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");

复制输入流到新文件

FileUtils.copyInputStreamToFile(input, f);

现在我可以使用这个文件进行进一步的测试

关于android - 如何从我的 android 测试项目的 Assets 文件夹加载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361289/

相关文章:

android - SQLite 异常 : no such table

android - Android找不到我的声音文件(和开发者)

android - 如何在 Robolectric 单元测试中断言 void 方法

从 R.attr 引用返回颜色资源 ID 的 Android 测试方法

android - 广告在底部导航中重叠显示

android - Gradle 项目刷新失败

android - kotlin + 改造 + 协程 + androidTest

android - 如何与另一个模块共享模块的 androidTest "Robots"?

java - Android——从 findViewById(R...) 分配的 SurfaceView 不允许访问自定义字段

android - matches(not(isDisplayed())) 失败并出现 NoMatchingViewException