简体   繁体   中英

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. So the call should look something like this:

String temp = MyClass.doSomething(MyObject[] objArray1);

But when I try to mock with PowerMockito like this:

@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:

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. It could alternatively be cast to Object for a varargs invocation But when I cast to an Object like this:

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.

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?

尝试这个

PowerMockito.doReturn("A String").when(MyClass.class, "doSomething", Matchers.anyObject());

This is normal. You need to pick Object... objs or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM