[英]How to use files in instrumented unit tests
I've got this project which processes images. 我有这个处理图像的项目。 The library I use to do most of the actual image processing requires me to run these tests on a Android device or emulator.
我用来完成大部分实际图像处理的库需要我在Android设备或模拟器上运行这些测试。 I'd like to provide a few test images which it should process, the thing is that I don't know how to include these files in the androidTest APK.
我想提供一些它应该处理的测试图像,问题是我不知道如何在androidTest APK中包含这些文件。 I could supply the images through the context/resources but I'd rather not pollute my projects resources.
我可以通过上下文/资源提供图像,但我宁愿不污染我的项目资源。 Any suggestions as to how to supply and use files in instrumented unit tests?
有关如何在仪表化单元测试中提供和使用文件的任何建议?
You can read asset files that are in your src/androidTest/assets
directory with the following code: 您可以使用以下代码读取
src/androidTest/assets
目录中的src/androidTest/assets
文件:
Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
InputStream testInput = testContext.getAssets().open("sometestfile.txt");
It is important to use the test's context as opposed to the instrumented application. 使用测试的上下文而不是仪表化的应用程序非常重要。
So to read an image file from the test asset directory you could do something like this: 因此,要从测试资产目录中读取图像文件,您可以执行以下操作:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.