如果您真的不想编写 getter 并且想要验证字段变量,您仍然可以通过反射访问类字段变量并对它们进行断言,如下所示:
目标类别:
public class TestMe{
private String value = null;
public void update(){
value = "hello";
}
}
测试:
public class TestMeTest {
@Test
public void testUpdate() throws NoSuchFieldException, IllegalAccessException {
TestMe testMe = new TestMe();
assertNull(getField(testMe, "value"));
testMe.update();
assertEquals("hello", getField(testMe, "value"));
}
private Object getField(Object root, String name) throws NoSuchFieldException, IllegalAccessException {
Field field = root.getClass().getDeclaredField(name);
field.setAccessible(true);
Object value = field.get(root);
field.setAccessible(false);
return value;
}
}