30

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?

  • Okay I got this working now as a raw resource (make sure to import `yourpackage.test.R`, not `yourpackage.R`). –  Jul 09 '14 at 21:14
  • 1
    Can you please explain me this in detail. I am badly stuck at this. I need separate assets for tests. How should I be configuring in gradle or any way possible? – Ramya K Sharma Feb 06 '15 at 08:52

2 Answers2

63

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.

Deprecation Note: As pointed out in the comments, these methods are now deprecated. This is the new recommended way:

  • First, instead of importing the old InstrumentationRegistry class, use the new one.
  • Instead of InstrumentationRegistry.getTargetContext(); use ApplicationProvider.getApplicationContext(). Source
  • For InstrumentationRegistry.getTargetContext();: In most scenarios, ApplicationProvider.getApplicationContext() should be used instead of the instrumentation test context. If you do need access to the test context for to access its resources, it is recommended to use PackageManager.getResourcesForApplication(String) instead. Source
Yair Kukielka
  • 10,686
  • 1
  • 38
  • 46
6

I think you use the wrong context ( the application-context and not the instrumentation context ) use:

getInstrumentation().getContext();

Or see here where I exactly do what you want to do: https://github.com/ligi/gobandroid/blob/master/android/src/androidTest/java/org/ligi/gobandroidhd/base/AssetAwareInstrumentationTestCase.java

ligi
  • 39,001
  • 44
  • 144
  • 244