Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

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

My project setup

  • Library Project A Contains a fooJSONParser like this :

    public class fooJsonParser {
      ...
      // Constructor using the input-stream
      public DPNodeJsonParser(InputStream inputJsonStream) {
        // Constructor
      }
    
      /**
       * Method that has to be executed once the class is instantiated to parse
       */
      public parsedObject parseObj() {
        // Parses and prints the info
      }
    
  • App Project B, which uses the Library Project A

Problem

Now I have created a Test Project tester to test the App Project B and add a test case to test the fooJsonParser class. Everytime there is new json data, I update the parse method and want to test it using the tester project and see if the parser is parsing correctly instead of installing, running the app and navigating to the screen where that new json data would be used. For accomplishing this, I am having a json file in the assets folder of the tester. But I'm not sure how I can read the json file. I think this has something to do with MockContext but wasn't sure how to use it as the documentation says all methods are non-functional.

Could somebody suggest a solution/provide a sample to read the asset file from a plain java object test case?

I'm fairly new to the android testing environment. Let me know If anything is unclear. I can add more information.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...