In Java, you can use a feature called reflection to manipulate visibility to get values for private fields and access private methods.
PowerMock provides these features in the WhiteBox class. (Reflection is used internally.)
SampleEm.java
public class SampleEm {
private String field = null;
public SampleEm(String filed) {
this.setField(filed);
}
public String getField() {
return field;
}
private void setField(String filed) {
this.field = filed;
}
}
getInternalState (instance, field name string)
@Test
public void test_getInternalState() throws Exception {
//Preparation
SampleEm em = new SampleEm("value");
//Get the value of a private field
String field = Whitebox.getInternalState(em, "field");
}
setInternalState (instance, field name string, set value)
@Test
public void test_setInternalState() throws Exception {
//Preparation
SampleEm em = new SampleEm("value");
//Set a value in the private field
Whitebox.setInternalState(em, "field", "newValue");
}
ʻInvokeMethod (instance, method name string, argument, ...) `
@Test
public void test_invokeMethod() throws Exception {
//Preparation
SampleEm em = new SampleEm("value");
//Call a private method
Whitebox.invokeMethod(em, "setField", "newValue");
}
Various other methods are provided.
You can access private fields / methods using reflection with your own code, but I think the advantage is that you can keep the test code simple by using Whitebox.
Recommended Posts