问题
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