Reputation: 377
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?
Upvotes: 15
Views: 5222
Reputation: 7044
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;
}
Upvotes: 33