使用返回整数列表的power mock测试私有方法
我有一个私有方法,它取一个整数值列表返回一个整数值列表。 我怎样才能使用power mock来测试它。 我是powermock的新手。我可以用简单的模拟进行测试..? 怎么样..
从文档中 ,在“Common – Bypass encapsulation”一节中:
使用Whitebox.invokeMethod(..)来调用实例或类的私有方法。
您也可以在同一部分中找到示例。
以下是如何执行此操作的完整示例:
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 methodCall(int num) { System.out.println("Call methodCall num: " + num); List 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 [] params = new CustomClass [] {…} WhiteboxImpl.invokeMethod(spy,“testmeMethod”,params)
由于params而无法工作。 你得到一个错误消息,表明testmeMethod与那个参数不存在看这里:
WhiteboxImpl类
public static synchronized 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正在理解软件工程”