我有一个处理图像的项目。我用来做大多数实际图像处理的库需要我在android设备或模拟器上运行这些测试。我想提供一些它应该处理的测试图像,问题是我不知道如何在androidtest apk中包含这些文件。我可以通过上下文/资源提供图像,但我不想污染我的项目资源。对于如何在插入指令的单元测试中提供和使用文件有什么建议吗?
最佳答案
您可以使用以下代码读取src/androidTest/assets
目录中的资产文件:
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
InputStream testInput = testContext.getAssets().open("sometestfile.txt");
使用测试的上下文而不是插入指令的应用程序是很重要的。
因此,要从测试资产目录中读取图像文件,可以执行以下操作:
public Bitmap getBitmapFromTestAssets(String fileName) {
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
AssetManager assetManager = testContext.getAssets();
InputStream testInput = assetManager.open(fileName);
Bitmap bitmap = BitmapFactory.decodeStream(testInput);
return bitmap;
}