Android Test Project - Reading assets file to test plain java object

后端 未结 3 660
忘了有多久
忘了有多久 2020-12-21 17:50

My project setup

  • Library Project A Contains a fooJSONParser like this :

    public class fooJsonParser {
      ...
      // Co         
    
    
            
3条回答
  •  执念已碎
    2020-12-21 17:55

    Suppose you have assets folder that contain json_sample.txt, If I recall, you can get it from a POJO by this:

    String testFile = "json_sample.txt";
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(testFile);
    

    I remember I did this in one of my project long times ago, not use if you need add assets/ as prefix of testFile, try it out.

    UPDATE:
    I just realized that the assets folder is no longer automatically added to project build path, probably since r14. I am pretty sure it was before (same as res folder). The file must under the build path, in order to make the code work, your need manually add assets folder into project build path, right click your project -- Build Path -- Configure Build Path, add assets folder as a Source folders on build path. or move your file into res folder alternatively.

    Android file system is quite restricted and I doubt if there is another way to read asserts file from a POJO.

提交回复
热议问题