比如某一类中有如下私有属性
private Position position;
使用set方法修改了position
public void setPosition(Position position) {
this.position = position;
checkRep();
}
如何在Junit程序中访问position,看其是否被修改?
代码如下:
Piece go = new Piece("fnd", 0, 1);
@Test
public void setPositionTest() {
Class<?> clazz = go.getClass();
Field field;
try {
field = clazz.getDeclaredField("position");
field.setAccessible(true);
Position old;
try {
old = (Position)field.get(go);
assertEquals(new Position(0, 1),old);
go.setPosition(new Position(2, 3));
Position newPosition = (Position)field.get(go);
assertEquals(new Position(2, 3),newPosition);
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
如图所示,可以通过