对用户定义的对象进行序列化Junit测试后,它失败了,并给了我结果
预期:com.me.Position@7a92922
实际:com.me.Position@25618e91
我定义了以下课程
public class Position {
private double x;
private double y;
/**
* default constructor
*/
public Position() {
}
/**
* paramterized constructor
*
* @param x
* x-coordinate
* @param y
* y-coordinate
*/
public Position(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
然后,我定义了另一个类来序列化和反序列化Position对象,该对象是上一类的实例,如下所示
public class PositionSerializer {
static void serialize(Position position, OutputStream outputStream) {
OutputStreamUtil.serializeDouble(position.getX(), outputStream);
OutputStreamUtil.serializeDouble(position.getY(), outputStream);
}
static Position deserialize(InputStream inputStream) {
double x = InputStreamUtil.deserializeDouble(inputStream);
double y = InputStreamUtil.deserializeDouble(inputStream);
Position positionObject = new Position();
positionObject.setX(x);
positionObject.setY(y);
return positionObject;
}
}
最后,我编写了如下的单元测试
public class PositionSerializerTest {
private InputStream iStream;
private ByteArrayOutputStream oStream;
@Before
public void init() {
oStream = new ByteArrayOutputStream();
}
Position serialzeAndDeserializeObject(Position positionObject) {
PositionSerializer.serialize(positionObject, oStream);
iStream = new ByteArrayInputStream(oStream.toByteArray());
return PositionSerializer.deserialize(iStream);
}
@Test
public void equals_equal() {
Position positionObject = new Position(5.5, 10.5);
Position deserializedPosition = serialzeAndDeserializeObject(positionObject);
assertThat(deserializedPosition).isEqualTo(positionObject);
}
}
怎么了?以及如何解决?
答案 0 :(得分:2)
没有错,但是您正在使用反序列化方法创建新实例:
Position positionObject = new Position();
这将始终调用Position Object的新实例,因此您无法使用==运算符进行比较
您应该重写equals方法,如下所示:
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Position)) {
return false;
}
Position otherObject = (Position)o;
if(this.x == otherObject.x && this.y == otherObject.y)
return true;
else return false;
}
然后致电:
assertThat(deserializedPosition).isEqualTo(positionObject);
答案 1 :(得分:2)
您正在检查不相等的引用相等性,因为您的反序列化方法在每次调用时都会返回新实例,请在下面使用它们比较值:
assertThat(deserializedPosition.getX()).isEqualTo(positionObject.getX())
assertThat(deserializedPosition.getY()).isEqualTo(positionObject.getY())
答案 2 :(得分:1)
看起来您的测试正在比较对象引用而不是对象值。覆盖equals函数或分别比较position对象中的每个值。