[英]Why do I get an argument type mismatch when I use arguments with PowerMockito mocked static method?
I am using PowerMockito to mock a call to a static class and the method has an argument that is an array of Objects. 我正在使用PowerMockito模拟对静态类的调用,并且该方法的参数是对象数组。 So the call should look something like this:
因此,呼叫应如下所示:
String temp = MyClass.doSomething(MyObject[] objArray1);
But when I try to mock with PowerMockito like this: 但是,当我尝试使用PowerMockito模拟时:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class TestClass {
@Test
public void myTest {
MyObject[] myObjArray1 = new MyObject[1];
myObjArray1[0] = new MyObject();
PowerMockito.mockStatic(MyClass.class);
PowerMockito.when(MyClass.class, "doSomething", myObjArray1).thenReturn("A String");
...
}
This gives me a warning in Eclipse: 这在Eclipse中给了我一个警告:
The argument of type MyObject[] should explicitly be cast to Object[] for the invocation of the varargs method when(Class, String, Object...) from type PowerMockito.
MyObject []类型的参数应显式转换为Object []以便从PowerMockito类型调用when(Class,String,Object ...)的varargs方法。 It could alternatively be cast to Object for a varargs invocation But when I cast to an Object like this:
也可以将其强制转换为Object以进行varargs调用,但是当我强制转换为这样的Object时:
PowerMockito.when(MyClass.class, "doSomething", (Object) objArray1).thenReturn("A String");
I am not having that string returned when this method executes, I'm assuming that this is because the Object type parameter causes the method to not be recognized because it is expecting something of type MyObject as a parameter. 我没有在执行此方法时返回该字符串,我假设这是因为Object类型参数导致无法识别该方法,因为它期望将MyObject类型的内容作为参数。
Any ideas of how to pass a non-primitive without casting as Object or how to get the method to be recognized with the cast? 关于如何在不强制转换为Object的情况下传递非基本类型或如何让强制转换识别方法的任何想法?
尝试这个
PowerMockito.doReturn("A String").when(MyClass.class, "doSomething", Matchers.anyObject());
This is normal. 这很正常。 You need to pick
Object... objs
or Object[] objs
. 您需要选择
Object... objs
或Object[] objs
。
Example... 例...
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String[] inputs = {" ", " ", " "};
method((Object) inputs);
method((Object[]) inputs);
}
static void method(Object... obj) {
System.out.println("obj.length = " + obj.length);
}
}
This prints.. 打印..
obj.length = 1
obj.length = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.