jeudi 24 septembre 2015

How do I use Powermock's Whitebox.invokeMethod(Object instance, Object... arguments) when my first method parameter is String type?

I would like to not explicitly name the method I am invoking in the invokeMethod() arguments. Powermock offers an overloaded invokeMethod() that infers the method based on the parameters passed.

invokeMethod(Object instance, Object... arguments)

The problem I am running into is that my first parameter is of type String. This invokes the invokeMethod() with the signature,

invokeMethod(Object instance, String methodToExecute, Object... arguments)

Here is a model of the test...

@Test
public void thisIsATest() throws Exception{
    TheClassBeingTested myClassInstance = new TheClassBeingTested();
    String expected = "60";
    String firstArgument = "123A48"; 

    ReturnType returnedTypeValue = Whitebox.invokeMethod(myClassInstance, firstArgument, AnEnum.TypeA);
    String actual = returnedTypeValue.getTestedField();
    assertEquals("Expected should be actual when AnEnum is TypeA", expected, actual);
}

This gives me the error,

org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name '123A48' with parameter types: [ AnEnum ] in class TheClassBeingTested.

I got it to work by changing the first parameter's type to Object, but this feels dirty to me.

@Test
public void thisIsATest() throws Exception{
    TheClassBeingTested myClassInstance = new TheClassBeingTested();
    String expected = "60";
    Object firstArgument = "123A48"; 

    ReturnType returnedTypeValue = Whitebox.invokeMethod(myClassInstance, firstArgument, AnEnum.TypeA);
    String actual = returnedTypeValue.getTestedField();
    assertEquals("Expected should be actual when AnEnum is TypeA", expected, actual);
}

Is there a correct way to pass a String type as the first argument while not hard coding my method name into the invokeMethod() call? I have found nothing in the Powermock documentation or forums addressing this, but it certainly cannot be all that uncommon.

Aucun commentaire:

Enregistrer un commentaire