Android Studio + Gradle and AndroidTest res/raw

ぐ巨炮叔叔 提交于 2020-01-17 02:53:08

问题


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?


回答1:


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();
        }

    }
}


来源:https://stackoverflow.com/questions/28993767/android-studio-gradle-and-androidtest-res-raw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!