[英]Comparing two observableLists in Junit
我试图使用assertEquals检查两个列表是否相同,这很好但是当试图将列表更改为observableList时,测试失败了。
那么如何比较JUnit中的两个可观察列表呢? 我想仅比较列表的内容。 基本上,这些observableLists包含Point对象,在Point类中我有hashCodeBuilder和equalsBuilder方法。 列表比较需要hashCode()
和equals()
方法,但我不确定ObservableList是否需要它们。
public class TestClass {
private MyClass myclass;
ObservableList<Point> TestPoints = FXCollections.observableArrayList();
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
myclass = new MyClass();
TestPoints.add(new Point(300.0,200.0));
TestPoints.add(new Point(600.0,500.0));
TestPoints.add(new Point(100.0,100.0));
TestPoints.add(new Point(200.0,200.0));
TestPoints.add(new Point(100.0,500.0));
TestPoints.add(new Point(600.0,100.0));
}
@Test
public void testClass() {
ObservableList<Point> expectedResult = FXCollections.observableArrayList();
expectedResult.add(new Point(100.0,100.0));
expectedResult.add(new Point(100.0,500.0));
expectedResult.add(new Point(600.0,500.0));
expectedResult.add(new Point(600.0,100.0));
ObservableList<Point> actualResult = FXCollections.observableArrayList();
actualResult = myclass.giftWrapping(TestPoints);
assertEquals(expectedResult, actualResult);
}
这是点类
public class Point {
private final DoubleProperty x;
private final DoubleProperty y;
public Point() {
this(0, 0);
}
public Point(double x, double y) {
this.x = new SimpleDoubleProperty(x);
this.y = new SimpleDoubleProperty(y);
}
@Override
public int hashCode() {
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
hashCodeBuilder.append(x);
hashCodeBuilder.append(y);
return hashCodeBuilder.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point) obj;
EqualsBuilder equalsBuilder = new EqualsBuilder();
equalsBuilder.append(x, other.x);
equalsBuilder.append(y, other.y);
return equalsBuilder.isEquals();
}
如果我使用List但是如果我使用了observableList则不起作用
基本上这个问题的问题在于equals和hashCode方法。 变量x和变量y必须转换为双精度,因为它们最初是DoubleProperty类型。 因此Point类中的equals和hashCode方法应如下所示
@Override
public int hashCode() {
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
hashCodeBuilder.append(x.doubleValue());
hashCodeBuilder.append(y.doubleValue());
return hashCodeBuilder.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point) obj;
EqualsBuilder equalsBuilder = new EqualsBuilder();
equalsBuilder.append(x.doubleValue(), other.x.doubleValue());
equalsBuilder.append(y.doubleValue(), other.y.doubleValue());
return equalsBuilder.isEquals();
}
这将使测试通过
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.