21

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

user882196
  • 1,691
  • 9
  • 24
  • 39
  • I think you would get more help if you gave a specific example of what you tried and what's not working. – jhericks Aug 18 '11 at 18:56

4 Answers4

31

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.

juppman
  • 163
  • 1
  • 8
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
12

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());
 }
Mindaugas Jaraminas
  • 3,261
  • 2
  • 24
  • 37
2
Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
Oded Breiner
  • 28,523
  • 10
  • 105
  • 71
  • 1
    I found that the class instance needs to be used rather than the class object. (i.e. myClassToBeTestedInstance instead of ClassToBeTested.class) – Rab Ross Apr 04 '16 at 10:54
  • is it expectedFooValue or it is parameters for theMethodToTest? – striker Jun 28 '22 at 07:08
0

When you want to test a private method with Powermockito and this private method has syntax:

private int/void testmeMethod(CustomClass[] params){
....
}

in your testing class method:

CustomClass[] params= new CustomClass[] {...} WhiteboxImpl.invokeMethod(spy,"testmeMethod",params)

will not work because of params. you get an error message that testmeMethod with that arguments doesn't exist Look here:

WhiteboxImpl class

public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments)
            throws Exception {
        return (T) doInvokeMethod(tested, null, methodToExecute, arguments);
    }

For arguments of type Array, PowerMock is messed up. So modify this in your test method to:

WhiteboxImpl.invokeMethod(spy,"testmeMethod",(Object) params)

You don't have this problem for parameterless private methods. As I can remember it works for parameters of type Primitve type and wrapper class.

"Understanding TDD is understanding Software Engineering"

ugurkocak1980
  • 143
  • 1
  • 13