How to provide data files for android unit tests

前端 未结 3 1373
逝去的感伤
逝去的感伤 2020-12-03 00:49

I am developing software that loads information from XML files using Android\'s implementation of java.xml.parsers.DocumentBuilder and DocumentBuilderFactory. I am writing

相关标签:
3条回答
  • 2020-12-03 01:12

    Option 1: Use InstrumentationTestCase

    Suppose you got assets folder in both android project and test project, and you put the XML file in the assets folder. in your test code under test project, this will load xml from the android project assets folder:

    getInstrumentation().getTargetContext().getResources().getAssets().open(testFile);
    

    This will load xml from the test project assets folder:

    getInstrumentation().getContext().getResources().getAssets().open(testFile);
    

    Option 2: Use ClassLoader

    In your test project, if the assets folder is added to project build path (which was automatically done by ADT plugin before version r14), you can load file from res or assets directory (i.e. directories under project build path) without Context:

    String file = "assets/sample.xml";
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
    
    0 讨论(0)
  • 2020-12-03 01:19

    For Android and JVM unit tests I use following:

    public final class DataStub {
        private static final String BASE_PATH = resolveBasePath(); // e.g. "./mymodule/src/test/resources/";
    
        private static String resolveBasePath() {
            final String path = "./mymodule/src/test/resources/";
            if (Arrays.asList(new File("./").list()).contains("mymodule")) {
                return path; // version for call unit tests from Android Studio
            }
            return "../" + path; // version for call unit tests from terminal './gradlew test'
        }
    
        private DataStub() {
            //no instances
        }
    
        /**
         * Reads file content and returns string.
         * @throws IOException
         */
        public static String readFile(@Nonnull final String path) throws IOException {
            final StringBuilder sb = new StringBuilder();
            String strLine;
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"))) {
                while ((strLine = reader.readLine()) != null) {
                    sb.append(strLine);
                }
            } catch (final IOException ignore) {
                //ignore
            }
            return sb.toString();
        }
    }
    

    All raw files I put into next path: ".../project_root/mymodule/src/test/resources/"

    0 讨论(0)
  • 2020-12-03 01:26

    Try this for Kotlin:

    val json = File("src\\main\\assets\\alphabets\\alphabets.json").bufferedReader().use { it.readText() }
    
    0 讨论(0)
提交回复
热议问题