繁体   English   中英

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

[英]How to read file from assets in test

嗨,我从资产读取文件时遇到问题。 每次我得到NullPointerException。 我用Roboletric,我已经在资产文件夹onBoard.json( 主/资产/ onBoard.jsontestAndroid /资产/ 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 你能给我一些建议吗? 非常感谢你。

我正在使用这种方法从资产读取文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM