How to provide data files for android unit tests

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);

Leave a Comment