简体   繁体   English

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

[英]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.

相关问题 如何在 Android Studio 中一键运行所有(单元和检测)测试 - how to run all (unit and instrumented) tests with one click in Android Studio Android仪表单元测试中的上下文和资源 - Context and Resource in Android Instrumented Unit Tests Dagger2可用于单元测试和仪表测试吗? - Can Dagger2 be used for unit tests and instrumented tests? 为什么要在 Android 中拆分单元测试和检测测试文件夹? - Why split unit tests and instrumented tests folders in Android? 在检测单元测试中访问上下文的更好方法是什么? - Which is a better way to access Context in instrumented unit tests? AssertEquals在仪器化单元测试的大字符串上提供TransactionTooLargeException - AssertEquals gives TransactionTooLargeException on big strings on Instrumented Unit Tests 在Android中编写完整测试(以单元为单位)的最佳实践是什么? - What is the best practice to write full tests(Unit-Instrumented) in android? 在 App Center 中运行 Android JVM(未检测)单元测试 - Run Android JVM (not instrumented) unit tests in App Center "如何访问 Android 中的缓存以进行检测测试?" - How to access cache in Android for instrumented tests? 如何授予对 android 仪器测试的权限? - How to grant permissions to android instrumented tests?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM