问题
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..
回答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.
回答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());
}
回答3:
Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
回答4:
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"
来源:https://stackoverflow.com/questions/7104985/testing-private-method-using-power-mock-which-return-list-of-integers