Search code examples
androidkotlinunit-testingandroid-unit-testing

Accessing a res/raw file from Unit tests


In my Android project, I have a file in res/raw/config.json. In Android application, this file can be accessed via resources.openRawResource().

Is there a way, how to access this file from Unit tests (not instrumented)? The file is present in the project on the computer, so it should be possible...

There is the obvious workaround, to copy the content of the file and inline it to the Tests.

I have come across the following code snippet on Gist but I am unable to figure out, what should be the fileName... the following is not working...

javaClass.classLoader?.getResourceAsStream("config.json") 
javaClass.classLoader?.getResourceAsStream("raw/config.json")
javaClass.classLoader?.getResourceAsStream("res/raw/config.json")  

Solution

  • In unit tests, you can't directly access resources using the res/raw/ path as you would in the regular Android code because unit tests run outside the Android runtime environment. However, you can use the ClassLoader to access files from the src/test/resources directory. Here's how you can do it:

    • Move the config.json file from res/raw/ to src/test/resources/ in your project.

    • Then you can access this file using the ClassLoader in your unit test using javaClass.classLoader?.getResourceAsStream("config.json")