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

后端 未结 3 652
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2020-12-21 17:59

    I got this solved by the following :

    • Created the setup as explained here
    • Extended the InstrumentationTestCase instead of TestCase. The InstrumentationTestCase has the method getInstrument() through which I got access to the Instrumentation's(The test app project) Context.
    0 讨论(0)
  • 2020-12-21 18:06

    Since Android Gradle Plugin version 1.1 you haven't to use Instrumentation to load file resource.

    I wrote here how to do it with POJO unit test case.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题