2013-04-26 42 views
4

我实现了一个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

回答

1
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); 
    } 

} 

然后使用下面的代码:

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

这个完美工作。我将该文件放置在测试项目的/ assets文件夹中,并能够通过此代码访问它。 – psunix 2013-04-27 07:22:07

0

,请使用以下代码:

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(); 
    }