我正在尝试在名为 MyUtil 的公共(public)最终类中测试一个方法:
private static String getStringFromArray(String[] array) {
String tempString = "";
if (array != null && array.length > 0) {
for (int i = 0; i < array.length - 1; i++) {
tempString += array[i] + ",";
}
tempString += array[array.length - 1];
}
return tempString;
}
我有两个使用 Whitebox 设置的测试方法来调用这个私有(private)方法:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyUtil.class)
public class MyUtilTests {
@Before
public void setUp() {
PowerMockito.spy(MyUtil.class);
}
@Test
public void getStringFromArrayReturnsEmptyStringIfArrayIsNullTest() throws Exception {
String[] arrayOfStrings = null;
String retVal = Whitebox.invokeMethod(MyUtil.class, "getStringFromArray", arrayOfStrings);
assertEquals("", retVal);
}
@Test
public void getStringFromArrayReturnsElementsSeparatedByCommasTest() throws Exception {
String[] arrayOfStrings = new String[]{"A", "B", "C"};
String retVal = Whitebox.invokeMethod(MyUtil.class, "getStringFromArray", arrayOfStrings);
assertEquals("A,B,C", retVal);
}
}
当我运行这些测试时,我收到一条错误消息:
“org.powermock.reflect.exceptions.MethodNotFoundException:找不到名称为“getStringFromArray”且参数类型为:[java.lang.String、java.lang.String、java.lang.String]的方法”
为什么 Whitebox 在第一个测试(以 null 作为数组)中识别该方法,但在第二个测试(我有一个实际的数组)中却不能识别?我应该提到的是,我包含了为此测试类制作的 @Before spy (我在其他测试中需要它),以防影响问题。
最佳答案
在 Eclipse 编辑器中,我在 Whitebox.invokeMethod 代码行看到以下警告
The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method invokeMethod(Class, String, Object...) from type Whitebox. It could alternatively be cast to Object for a varargs invocation
因此,当我通过在传递参数时将类型转换为对象来更改两个测试方法的代码行时,测试用例成功执行。
String retVal = Whitebox.invokeMethod(MyUtil.class, "getStringFromArray", (Object)arrayOfStrings);
关于java - 为什么 Whitebox 无法识别我的私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861799/