How can I load a json file from an android unit test that is run with PowerMockRunner?

泪湿孤枕 提交于 2019-12-10 10:30:08

问题


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?


回答1:


You have two options:

  • try to get system classloader via ClassLoader.getSystemClassLoader()
  • Get classloader from the class that has been ignored by PowerMock. By default:

"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.*"

Or you may use @PowerMockIgnore.



来源:https://stackoverflow.com/questions/36295824/how-can-i-load-a-json-file-from-an-android-unit-test-that-is-run-with-powermockr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!