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.
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.
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.
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.