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. 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. 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?
Unit tests cannot test the UI for your app without mocking objects such as an Activity. Instrumentation tests run on a device or an emulator. In the background, your app will be installed and then a testing app will also be installed which will control your app, lunching it and running UI tests as needed.
Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.
You can read asset files that are in your src/androidTest/assets
directory with the following code:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With