Assets folder in Android Studio Unit Test

user1837158 picture user1837158 · Jul 7, 2014 · Viewed 7.6k times · Source

I have a Gradle project with the following structure:

project/
    src/
        androidTest/
            java/
        main/
            java/
            res/
            AndroidManifest.xml
    build.gradle

Now I want to add a unit test which uses a resource (either "raw" or "asset").

I put my resource into project/androidTest/assets/test_file and access it with getContext().getResources().getAssets().open("test_file"); (in an AndroidTestCase).

However, this gives me a FileNotFoundException. How can I fix this?

Answer

Yair Kukielka picture Yair Kukielka · Feb 29, 2016

It looks like you're trying to create an instrumented unit test, since you want to create it in the androidTest folder.

You can use one of these two lines in your test to get the context:

  • Context ctx = InstrumentationRegistry.getTargetContext(); this one will give you your app's context. You can use it to grab assets that are in src/main/assets for example.

  • Context ctx = InstrumentationRegistry.getContext(); this one will give you the test app's context. You can use it to grab assets that are in src/androidTest/assets

If you want to know more about assets in unit testing you can read this post. In this github file you have an example.