如何在检测单元测试中使用文件

Mat*_*ijs 9 android unit-testing android-instrumentation

我有这个处理图像的项目.我用来执行大多数实际图像处理的库需要在Android设备或模拟器上运行这些测试.我想提供一些它应该处理的测试图像,问题是我不知道如何在androidTest APK中包含这些文件.我可以通过上下文/资源提供图像,但我宁愿不污染我的项目资源.有关如何在仪表化单元测试中提供和使用文件的任何建议?

dit*_*kin 21

您可以src/androidTest/assets使用以下代码读取目录中的资产文件:

Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
InputStream testInput = testContext.getAssets().open("sometestfile.txt");
Run Code Online (Sandbox Code Playgroud)

使用测试的上下文而不是仪表化的应用程序非常重要.

因此,要从测试资产目录中读取图像文件,您可以执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)