Mathijs Mathijs - 1 year ago 80
Android Question

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 met 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?

Answer Source

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 =;
   Bitmap bitmap = BitmapFactory.decodeStream(testInput);

   return bitmap;