首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓单元测试资源文件访问"InvocationTargetException“

安卓单元测试资源文件访问"InvocationTargetException“
EN

Stack Overflow用户
提问于 2018-07-31 19:17:16
回答 1查看 131关注 0票数 1

JUnitTest/Mockito/PowerMockito::"InvocationTargetException“尝试从android中的res/文件访问dataSet json文件,但获取到

代码语言:javascript
复制
InputStream in = this.getClass().getClassLoader().getResourceAsStream("resource.json");
        try {
            Reader reader = new InputStreamReader(in, "UTF-8");
            ConfigModel result  = new Gson().fromJson(reader, ConfigModel.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

EN

回答 1

Stack Overflow用户

发布于 2018-08-01 08:25:06

编辑:更新版本。如果你使用Android工具测试,你可以得到context,你可以这样做,

代码语言:javascript
复制
@Test
public void someTest() {
    // Context of the app under test. 
    // In this case put your resource in your app's assets folder src/main/assets
    Context appContext = InstrumentationRegistry.getTargetContext();

    / **
    * Context of the test app. 
    * In this case put your resource in your test app's assets folder src/androidTests/assets
    * Context appContext = InstrumentationRegistry.getContext();
    **/

    InputStream in = null;
    try {
        in = appContext.getAssets().open("resource.json");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

如果你不想进入安卓测试的方式,简单的方法是将你的resource.json放在src/test/resources文件夹下,然后你的上面的代码就可以工作了。就像这样。

代码语言:javascript
复制
@Test
public void test() {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream res = classLoader.getResourceAsStream("testFlags.json");
}

我围绕这些做了一些测试,我可以说它们工作得很好。让我知道进展如何。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51612140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档