psu*_*nix 5 testing android json
我实现了一个JSON接口,用于在我的一个Android项目中通过http获取模型数据.
这项工作到目前为止,我想写一些测试.我按照android文档中的建议创建了一个测试项目.为了测试JSON接口,我需要一些测试数据,我想把它放在一个文件中.
我的研究表明,最好把这些文件放在android测试项目的assets文件夹中.要访问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);
...
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我在尝试访问"models.json"文件时遇到"没有这样的文件或目录(2)"错误.(/assets/models.json)
获取可用文件列表时
String[] list = res.getAssets().list("");
Run Code Online (Sandbox Code Playgroud)
"models.json"列在那里.
我正在Android 4.2.2 api级别17上运行这些测试.
小智 2
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码:
JSONObject json = new JSONObject(Util.readFileFromAssets("abc.txt", getApplicationContext()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2377 次 |
| 最近记录: |