TargetClass.java
private String privateMethod(String message) {
return "Input: " + message;
}
TargetClassTest.java
@Test
public void privateMethodTest() {
// 1.Create an instance of the implementation class
TargetClass targetClass = new TargetClass();
// 2.Create an instance of a private method
Method privateMethod = TargetClass.class.getDeclaredMethod("privateMethod", String.class);
// 3.Allow access to private methods
privateMethod.setAccessible(true);
// 4.Pass the implementation class instance and method arguments to the instantiated method
String actual = (String) privateMethod.invoke(targetClass, "Oh my god.");
String expected = "Input: Oh my god.";
// Assert
assertEquals(expected, actual);
}
Recommended Posts