如何从使用PowerMockRunner运行的Android单元测试中加载json文件? [英] How can I load a json file from an android unit test that is run with PowerMockRunner?
问题描述
我正在使用PowerMockRunner运行我的单元测试。我想从资产文件夹中加载一些罐装网络响应json文件。
I am using PowerMockRunner to run my unit tests. I want to load some canned network response json files from my assets folder.
我正在使用此方法尝试获取文件。
I am using this method to try to get the file.
private static File getFileFromPath(Object obj, String fileName) {
ClassLoader classLoader = obj.getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
return new File(resource.getPath());
}
我从我的类中调用像这样的方法,该方法在顶部有这些注释
I call the method like this from my class which has these annotations at the top.
@RunWith(PowerMockRunner.class)
@PrepareForTest(Network.class)
File file = getFileFromPath(this, "mock_response.json");
但是,当我评估此表达式时。
However, when I evaluate this expression.
classLoader.getResource(".");
这表明我在运行此测试时当前位于此目录中。
It shows that I am currently in this the directory below while running this test.
/Users/tylerpfaff/Library/Android/sdk/platforms/android-23/data/res/
由于我位于平台资源目录中,因此我没有希望从项目的资源目录中成功加载资源。
Seeing as I'm in the platforms resource directory, there is no hope of me successfully loading my resources from my project's resource directory. What do I need to do to access my resource directory of my project?
推荐答案
您有两个选择:
- 尝试通过
ClassLoader.getSystemClassLoader()
获取系统类加载器 - 从PowerMock忽略的类中获取类加载器。默认情况下:
org.hamcrest。, java。 ,
javax.accessibility。, sun。, org.junit。, org.testng。,
junit。, org.pitest。, org.powermock.modules.junit4.common.internal。,
org.powermock.modules.junit3。。 internal.PowerMockJUnit3RunnerDelegate ,
org.powermock.core *, org.jacoco.agent.rt。*
"org.hamcrest.", "java.", "javax.accessibility.", "sun.", "org.junit.", "org.testng.", "junit.", "org.pitest.", "org.powermock.modules.junit4.common.internal.", "org.powermock.modules.junit3.internal.PowerMockJUnit3RunnerDelegate", "org.powermock.core*", "org.jacoco.agent.rt.*"
或者您可以使用 @PowerMockIgnore
。
这篇关于如何从使用PowerMockRunner运行的Android单元测试中加载json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!