【问题标题】:How to read file from assets in test如何从测试中的资产中读取文件
【发布时间】:2016-10-17 13:39:32
【问题描述】:

您好,我在从资产中读取文件时遇到问题。每次我得到 NullPointerException。 我使用 Roboletric,并且在资产文件夹中有 onBoard.jsonmain/assets/onBoard.jsontestAndroid/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!这里是空指针InputStream。 你能给我一些建议吗? 非常感谢。

【问题讨论】:

  • assert 文件夹?????
  • 对不起,我的意思是assets
  • 这方面有什么更新吗?你找到解决办法了吗?

标签: android unit-testing robolectric


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 2023-03-11
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多