如何从测试中的资产中读取文件

时间:2016-10-17 13:39:32

标签: android unit-testing robolectric

您好我从资产中读取文件有问题。每次我得到NullPointerException。 我使用Roboletric,我在assets文件夹中有 onBoard.json main / assets / onBoard.json testAndroid / assets / onBoard.json ) 。这是我的测试类,基本测试打开文件。

@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
public class JsonUtilsTest extends Instrumentation {

@Test
public void readAssetsFileInAndroidTestContextTest() throws IOException {

    ShadowApplication application = ShadowApplication.getInstance();
    assertNotNull(application);
    InputStream input = application.getApplicationContext().getAssets().open("onBoard.json");
    assertNotNull(input);
}


@Test
public void strawberryTest() throws Exception {
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("onBoard.json");

}

@Test
public void shouldGetJSONFromAssetTest() throws Exception{
    assertNotNull(RuntimeEnvironment.application); //Getting the application context
    InputStream input = RuntimeEnvironment.application.getAssets().open("onBoard.json");// the file name in asset folder
    assertNotNull(input);
}
}

并记录消息:

java.lang.NullPointerException
at org.robolectric.shadows.ShadowAssetManager.open(ShadowAssetManager.java:179)
at android.content.res.AssetManager.open(AssetManager.java)
...

所有这个方法都返回NullPointerException!这是nullPointer InputStream。 你能给我一些建议吗? 非常感谢你。

1 个答案:

答案 0 :(得分:0)

我正在使用此方法从资产中读取文件:

private String readTxt() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int i;
    try {
        AssetManager mngr = getAssets();
        InputStream inputStream = mngr.open("Your file name.json");

        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.e(TAG, byteArrayOutputStream.toString());
    return byteArrayOutputStream.toString();
}