Monish Das
Monish Das

Reputation: 393

Mocking a private method

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)

Upvotes: 0

Views: 1337

Answers (2)

Monish Das
Monish Das

Reputation: 393

After lot of research I found the solution. We need to add the following as dependency in the pom.xml to prevent this error... **

<dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.18.2-GA</version>
        </dependency>

**

Upvotes: 0

kswaughs
kswaughs

Reputation: 3087

Your test code looks like you are using PowerMock EasyMock. But your post is also tagged with mockito & powermockito.

I am giving below solution using powermockito.

Main Java class :

public class TestLoad {

private static List<String> myList = new ArrayList<String>();
private static final String filename = "/myfile.txt";

public List<String> generateList(Abc abc) throws Exception {

    System.out.println("generateList method is called");
    return populateList();
}

private List<String> populateList() {
    System.out.println("populateList method is called");
    ClassLoader classLoader = TestLoad.class.getClassLoader();
    File listfile = new File(classLoader.getResource(filename).getFile());
    // Read listfile and build localList logic here
    List<String> localList = new ArrayList<String>();

    return localList;
 }
}

Test Java class

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@PrepareForTest(TestLoad.class)
@RunWith(PowerMockRunner.class)
public class TestLoadTest {

@Test
public void testPrivateMethod() throws Exception{

    List<String> testList = new ArrayList<String>();
    testList.add("00");

    TestLoad mockInstance = PowerMockito.spy(new TestLoad());

    PowerMockito.doReturn(testList).when(mockInstance, "populateList");

    List<String> outputList = mockInstance.generateList(new Abc());

    System.out.println("test output:" + outputList);

    PowerMockito.verifyPrivate(mockInstance, Mockito.times(1)).invoke("populateList"); 

}

}

console output :

generateList method is called
test output:[00]

Upvotes: 0

Related Questions