2013-04-26 46 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(); 
    }