Search code examples
javaunit-testingpowermockitowhite-box

Why doesn't Whitebox recognize my private method?


I have a method that I am trying to test in a public final class called MyUtil:

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;
}

And I have two test methods that I have setup using Whitebox to invoke this private method:

@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);
  }
}

When I run these tests I get an error message that says:

"org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name 'getStringFromArray' with parameter types: [ java.lang.String, java.lang.String, java.lang.String ]"

Why does Whitebox recognize the method in the first test (with null as the array) but not in the second (where I have an actual array)? I should mention that I included the @Before spy that I made for this test class (I need it in other tests) just in case that is influencing the problem.


Solution

  • In Eclipse editor, I see this below warning at Whitebox.invokeMethod line of code

    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

    So, When I changed the line of code as below for the two test methods by type casting to Object when passing the arguments, test cases executed successfully.

     String retVal = Whitebox.invokeMethod(MyUtil.class, "getStringFromArray", (Object)arrayOfStrings);