Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android测试访问json文件_Android_Json_Testing - Fatal编程技术网

android测试访问json文件

android测试访问json文件,android,json,testing,Android,Json,Testing,我在一个android项目中实现了一个JSON接口,用于通过http获取模型数据 到目前为止,这是可行的,我想写一些测试。我按照android文档中的建议创建了一个测试项目。为了测试JSON接口,我需要一些测试数据,我想把它们放在一个文件中 我的研究表明,最好将这些文件放在android测试项目的资产文件夹中。要访问资产文件夹中的文件,应通过InstrumentationTestCase扩展测试类。然后,应该可以通过对资源对象调用getAssets().open()来访问这些文件。所以我想出了以

我在一个android项目中实现了一个JSON接口,用于通过http获取模型数据

到目前为止,这是可行的,我想写一些测试。我按照android文档中的建议创建了一个测试项目。为了测试JSON接口,我需要一些测试数据,我想把它们放在一个文件中

我的研究表明,最好将这些文件放在android测试项目的资产文件夹中。要访问资产文件夹中的文件,应通过InstrumentationTestCase扩展测试类。然后,应该可以通过对资源对象调用getAssets().open()来访问这些文件。所以我想出了以下代码:

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);
    ...
  }
}
不幸的是,我在尝试访问“models.json”文件时遇到了一个“no-this file or directory(2)”错误。(/assets/models.json)

通过获取可用文件的列表时

String[] list = res.getAssets().list("");
其中列出了“models.json”

我正在Android 4.2.2 api级别17上运行这些测试。

请使用以下代码:

AssetManager assetManager = getResources().getAssets();
InputStream InputStream=null

try {
    inputStream = assetManager.open("foo.txt");
        if ( inputStream != null)
            Log.d(TAG, "It worked!");
    } catch (IOException e) {
        e.printStackTrace();
    }
然后使用以下代码:

JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));

这很有效。我将文件放在测试项目的/assets文件夹中,并能够通过此代码访问它。
JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));