我实现了一个JSON接口,通过http在我的一个android项目中获取模型数据。android测试访问json文件
这工作到目前为止,我想写一些测试。我按照android文档中的建议创建了一个测试项目。为了测试JSON接口,我需要一些我想放在文件中的测试数据。
我的研究显示,最好将这些文件放在android测试项目的assets文件夹中。要访问资产文件夹中的文件,应该通过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”文件时,不幸的是,我得到一个“没有这样的文件或目录(2)”的错误。 (/assets/models.json)
获得可用文件列表时通过
String[] list = res.getAssets().list("");
“models.json” 被列在那里。
我在Android 4.2.2 API级别运行这些测试17
这个完美工作。我将该文件放置在测试项目的/ assets文件夹中,并能够通过此代码访问它。 – psunix 2013-04-27 07:22:07