gpt4 book ai didi

android - Android单元测试中资源文件访问 "InvocationTargetException"

转载 作者:行者123 更新时间:2023-11-29 23:43:57 25 4
gpt4 key购买 nike

JUnitTest/Mockito/PowerMockito:: 尝试从 android 中的 res/raw 文件访问数据集 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 仪器测试,那么您可以获得 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");
}

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

关于android - Android单元测试中资源文件访问 "InvocationTargetException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51612140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com