Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 838
Mathijs Avatar asked May 30 '16 14:05

Mathijs


People also ask

What is the difference between unit tests and instrumented 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.

What is an instrumented test?

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.


1 Answers

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;
}
like image 167
ditkin Avatar answered Sep 30 '22 09:09

ditkin