JUnitTest/Mockito/PowerMockito::"InvocationTargetException“尝试从android中的res/文件访问dataSet json文件,但获取到
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();
}
发布于 2018-08-01 08:25:06
编辑:更新版本。如果你使用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();
}
}
如果你不想进入安卓测试的方式,简单的方法是将你的resource.json
放在src/test/resources
文件夹下,然后你的上面的代码就可以工作了。就像这样。
@Test
public void test() {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream res = classLoader.getResourceAsStream("testFlags.json");
}
我围绕这些做了一些测试,我可以说它们工作得很好。让我知道进展如何。
https://stackoverflow.com/questions/51612140
复制相似问题