Tuesday, April 23, 2013

Unit tests for private methods in JAVA


Here is the easy way of testing  private methods in a java class using reflection

public class MyBoundry {
String returnValue ="hello";

private String getBoundryName(String name) {
return returnValue +name;
}

}

public class MyBoundryTest {
  @Test
  public void shouldMyBoundryReturnsExpectedStringValue(){
    Method method =   MyBoundry.class.getDeclaredMethod("getBoundryName", String.class);
    method.setAccessible(true);  
          MyBoundry myBoundry = new MyBoundry();
    assertEquals("helloboundry", method.invoke(myBoundry, "boundry"));
}
}

No comments:

Post a Comment