【发布时间】:2011-10-29 14:50:31
【问题描述】:
我有一个私有方法,它采用整数值列表返回整数值列表。我如何使用 power mock 来测试它。我是 powermock 的新手。我可以用简单的模拟进行测试吗..?怎么样..
【问题讨论】:
-
我认为,如果您提供一个具体示例说明您尝试过的方法和无效的方法,您会获得更多帮助。
我有一个私有方法,它采用整数值列表返回整数值列表。我如何使用 power mock 来测试它。我是 powermock 的新手。我可以用简单的模拟进行测试吗..?怎么样..
【问题讨论】:
【讨论】:
这是一个完整的例子:
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());
}
【讨论】:
Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
【讨论】:
当你想用 Powermockito 测试一个私有方法并且这个私有方法有语法时:
private int/void testmeMethod(CustomClass[] params){
....
}
在您的测试类方法中:
CustomClass[] 参数= new CustomClass[] {...} WhiteboxImpl.invokeMethod(spy,"testmeMethod",params)
由于参数而无法工作。您收到一条错误消息,表明带有该参数的 testmeMethod 不存在 看这里:
WhiteboxImpl 类
public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments)
throws Exception {
return (T) doInvokeMethod(tested, null, methodToExecute, arguments);
}
对于 Array 类型的参数,PowerMock 搞砸了。因此,在您的测试方法中将其修改为:
WhiteboxImpl.invokeMethod(spy,"testmeMethod",(Object) params)
对于无参数的私有方法,你没有这个问题。我记得它适用于 Primitve 类型和包装类的参数。
“理解 TDD 就是理解软件工程”
【讨论】: