How to access files from assets folder during tests execution?

后端 未结 8 2082
旧时难觅i
旧时难觅i 2021-02-01 20:25

How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing t

相关标签:
8条回答
  • 2021-02-01 21:11

    Updating as for Roboelectric 3.1

        @Test
        public void shouldGetJSONFromAsset() throws Exception{
             Assert.assertNotNull(RuntimeEnvironment.application); //Getting the application context
             InputStream input = RuntimeEnvironment.application.getAssets().open("fileName.xml");// the file name in asset folder
             Assert.assertNotNull(input);
            }
    

    See also

    1. 2.4 to 3.0 Upgrade Guide
    2. 3.0 to 3.1 Upgrade Guide

    de Guide

    0 讨论(0)
  • 2021-02-01 21:15

    If everything is correct, then you'll need something like this to read it:

    public String readFileFromAssets(String fileName, Context context) throws IOException {
        InputStreamReader stream = new InputStreamReader(context.getAssets().open(fileName));
        Preconditions.checkNotNull(stream, "Stream is null");
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        return IOUtils.toString(reader);
    }
    

    You need to pass Context for it to work.

    Another thing to verify if you have configured assets in Gradle correctly? Here is just an example:

    sourceSets {
        main {
            java.srcDirs = ['src/main']
            // can be configured in different way
            assets.srcDirs = ['src/androidTest/assets']
            // other things, examples
            res.srcDirs = ['res']
            manifest.srcFile 'AndroidManifest.xml'
        }
    }
    
    0 讨论(0)
提交回复
热议问题