Testing private method using power mock which return list of Integers

39,340

Solution 1

From the documentation, in the section called "Common - Bypass encapsulation":

Use Whitebox.invokeMethod(..) to invoke a private method of an instance or class.

You can also find examples in the same section.

Solution 2

Here is a full example how to do to it:

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

import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;

class TestClass {
    private List<Integer> methodCall(int num) {
        System.out.println("Call methodCall num: " + num);
        List<Integer> result = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            result.add(new Integer(i));
        }
        return result;
    }
}

 @Test
 public void testPrivateMethodCall() throws Exception {
     int n = 10;
     List result = Whitebox.invokeMethod(new TestClass(), "methodCall", n);
     Assert.assertEquals(n, result.size());
 }

Solution 3

Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
Share:
39,340
user882196
Author by

user882196

Updated on July 09, 2022

Comments

  • user882196
    user882196 almost 2 years

    I have a private method which take a list of integer value returns me a list of integer value. How can i use power mock to test it. I am new to powermock.Can i do the test with easy mock..? how..

  • Rab Ross
    Rab Ross about 8 years
    I found that the class instance needs to be used rather than the class object. (i.e. myClassToBeTestedInstance instead of ClassToBeTested.class)
  • Evgeniy Mishustin
    Evgeniy Mishustin about 8 years
    the link is dead now
  • striker
    striker about 2 years
    is it expectedFooValue or it is parameters for theMethodToTest?