I am trying to mock a method which internally calls a private method. This private method reads a file using classloader.getclass method and populates a list which is a static variable of the class. I tried all possible ways to mock this private method but it doesn't seem to work.
class TestLoad {
private static List <String> myList = new ArrayList <String> ();
private static final String filename = "/myfile.txt";
public XYZ generateList(Abc abc) throws Exception {
populateList();
}
private populateList() {
ClassLoader classLoader = TestLoad.class.getClassLoader();
File listfile = new File(classLoader.getResource(
filename).getFile());
List <String> localList = new ArrayList <String> ();
try (Scanner scanner = new Scanner(listfile)) {
while (scanner.hasNextLine()) {
String text = scanner.nextLine();
localList.add(text.trim());
}
scanner.close();
} catch (IOException e) {}
return localList;
}
}
I am trying to mock populateList() but all the time the control enters into the method. I tried almost all the options on the net by both mockito and powermock but it doesn't seem to work.My Junit is as below
Class start has @RunWith(PowerMockRunner.class) @PrepareForTest(TestLoad.class) ArrayList testList = new ArrayList(); testList.add("00"); TestLoad instance = PowerMock.createPartialMock(TestLoad.class,"populateList"); PowerMock.expectPrivate(instance, "populateList").andReturn( testList); PowerMock.replay(instance);
Below is the log for reference:
java.lang.IllegalStateException: Failed to transform class with name com.xyz.TestLoad. Reason: java.io.IOException: invalid constant type: 18 at 17 at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:266) at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:180) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:68) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:145) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:40) at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:244) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.(JUnit4TestSuiteChunkerImpl.java:61) at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.(AbstractCommonPowerMockRunner.java:32) at org.powermock.modules.junit4.PowerMockRunner.(PowerMockRunner.java:34) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)