Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android testing accessing json file

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.

like image 425
psunix Avatar asked Nov 02 '22 23:11

psunix


1 Answers

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()));
like image 87
Yajneshwar Mandal Avatar answered Nov 11 '22 12:11

Yajneshwar Mandal