0

I have an Android app. And I want to write instrumentation tests.

I want to put some specific files in the res/rawfolder for the test apk.

I place them in the androidTest/src/res/raw folder and reference them in code with R.raw.file. However the app references some other resource file, which one in my main source set.

How can I ensure that my test apk gets the proper files from its own res/raw folder?

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169
Tiago Veloso
  • 8,513
  • 17
  • 64
  • 85

1 Answers1

6

Your path is wrong. The path you want is src/androidTest/res/raw.

Files in this directory will replace files in the src/main/res/raw.

New files in this directory, need to be accessed by the R class in the test package and not the app's R file.

-- update

If the problem is that the Android Studio tells you that the R class does not exist in the test package, then that is caused by Android Studio not building the test R class until you try to run the unit tests. Fix this by ignoring the errors on the screen and try to run the test. The R class will be generated and the tests will run (assuming the were no other errors).

If the problem is that reading the file produces the wrong contents, then you're reading the file from the wrong context. You need to use getContext from Instrumentation.

public class ResourceLoadTest extends InstrumentationTestCase {

    public void testLoadResource() throws IOException {
        InputStream inputStream = getInstrumentation().getContext().getResources().openRawResource(com.example.app.test.R.raw.hello);
        try {
            Scanner scanner = new Scanner(inputStream, "UTF-8");
            assertEquals("hello", scanner.nextLine());
        } finally {
            inputStream.close();
        }

    }
}
MiguelSlv
  • 14,067
  • 15
  • 102
  • 169
Michael Krussel
  • 2,586
  • 1
  • 14
  • 16
  • My path was a typo I have it like that. The thing is I Can't seem to access my test package R's class. – Tiago Veloso Mar 12 '15 at 15:59
  • Your update is worth gold. Was always wondering why it worked on some projects, while it doesn't seem to work on others. Then suddenly, out of *nothing* it started to work. Never figured out the root cause of this. – Rafael T May 25 '18 at 14:55