【发布时间】:2017-11-16 15:36:55
【问题描述】:
我正在使用 Spock 框架编写一个测试,在测试列表的相等性时发现了一个奇怪的问题。
当我比较两个列表时
sourceList == targetList
并且这些列表包含相同类型的 Comparable 对象,这些对象使用其 compareTo 方法而不是 equals 进行相等性测试。
在对此类列表进行相等性测试时,是否有任何简单的方法可以强制 Groovy 使用 equals?
这是一个简单的测试规范,其中测试应该失败,但事实并非如此。
class Test extends Specification {
def "list test"() {
when:
def listA = [[index: 1, text: "1"] as Bean, [index: 2, text: "2"] as Bean]
def listB = [[index: 1, text: "1"] as Bean, [index: 2, text: "3"] as Bean]
then:
listA == listB
}
class Bean implements Comparable<Bean> {
int index
String text
@Override
public int compareTo(Bean o) {
return index.compareTo(o.index);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + index;
result = prime * result + ((text == null) ? 0 : text.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Bean)) {
return false;
}
Bean other = (Bean) obj;
if (index != other.index) {
return false;
}
if (text == null) {
if (other.text != null) {
return false;
}
} else if (!text.equals(other.text)) {
return false;
}
return true;
}
}
}
【问题讨论】:
-
你能提供一个可重现的样本吗?
-
@Rao 查看编辑后的问题
-
感谢您的编辑,您使用的是 java 还是 groovy?
标签: groovy