I implemented a JSON interface for getting model data over http in one of my android projects.
this works so far and I would like to write some tests. I created a test project as suggested in the android documentation. for testing the JSON interface I need some test data which I would like to put in a file.
my research showed up that it's best to put these files in the assets folder of the android test project. to access files in the assets folder one should extend the test class by InstrumentationTestCase. then it should be possible to access the files by calling getAssets().open() on a resources object. so I came up with the following code:
public class ModelTest extends InstrumentationTestCase {
public void testModel() throws Exception {
String fileName = "models.json";
Resources res = getInstrumentation().getContext().getResources();
InputStream in = res.getAssets().open(fileName);
...
}
}
unfortunately I'm getting an "no such file or directory (2)" error when trying to access "models.json" file. (/assets/models.json)
when getting a list of the available files by
String[] list = res.getAssets().list("");
"models.json" is listed in there.
I'm running these tests on Android 4.2.2 api level 17.
public static String readFileFromAssets(String fileName, Context c) {
try {
InputStream is = c.getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
return text;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Then use the following code:
JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With