【问题标题】:Resource File access "InvocationTargetException" in Android Unit TestAndroid单元测试中的资源文件访问“InvocationTargetException”
【发布时间】:2018-07-31 11:17:16
【问题描述】:

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

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

【问题讨论】:

    标签: android mockito powermockito


    【解决方案1】:

    编辑:更新版本。 如果您使用 Android 仪器测试,那么您可以获得context,您可以执行以下操作,

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

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

    @Test
    public void test() {
            ClassLoader classLoader = this.getClass().getClassLoader();
            InputStream res = classLoader.getResourceAsStream("testFlags.json");
    }
    

    我围绕这些进行了一些测试,我可以说它们运行良好。告诉我进展如何。

    【讨论】:

    • 嗨 Abhishek,您是否使用 Mockito/PowerMockitoRunner 检查了此代码以进行单元测试?
    • 嗨阿米特,我更新了我的答案,看看,让我知道它是怎么回事。
    • 对于仪器测试,您的代码没问题,但对于 JUnit,它不起作用。我只要求进行junit测试...
    • 好吧,我的错,你必须把你的resource.json文件放在src/test/resources文件夹下。 dropbox.com/s/c5mih513kzg80f1/Resource.png?dl=0 附上通过测试的截图和我的目录结构。更正了答案。
    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    相关资源
    最近更新 更多