如何在检测单元测试中使用文件
How to use files in instrumented unit tests
我有这个处理图像的项目。我用来进行大部分实际图像处理的库要求我在 Android 设备或模拟器上 运行 这些测试。我想提供一些它应该处理的测试图像,问题是我不知道如何将这些文件包含在 androidTest APK 中。我可以通过 context/resources 提供图像,但我不想污染我的项目资源。关于如何在检测单元测试中提供和使用文件有什么建议吗?
您可以使用以下代码读取 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;
}
我有这个处理图像的项目。我用来进行大部分实际图像处理的库要求我在 Android 设备或模拟器上 运行 这些测试。我想提供一些它应该处理的测试图像,问题是我不知道如何将这些文件包含在 androidTest APK 中。我可以通过 context/resources 提供图像,但我不想污染我的项目资源。关于如何在检测单元测试中提供和使用文件有什么建议吗?
您可以使用以下代码读取 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;
}