【问题标题】:How to use files in instrumented unit tests如何在检测单元测试中使用文件
【发布时间】:2016-05-30 14:01:41
【问题描述】:
我有这个处理图像的项目。我用来进行大部分实际图像处理的库需要我在 Android 设备或模拟器上运行这些测试。我想提供一些它应该处理的测试图像,问题是我不知道如何将这些文件包含在 androidTest APK 中。我可以通过上下文/资源提供图像,但我不想污染我的项目资源。关于如何在检测单元测试中提供和使用文件有什么建议吗?
【问题讨论】:
标签:
android
unit-testing
android-instrumentation
【解决方案1】:
您可以使用以下代码读取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;
}