我有一个字符串-数字对的类。该类实现了 compareTo
方法。
另一个类的方法返回pair类型的元素集合。
我想对此方法执行单元测试,因此编写了以下内容:
@Test
public void testWeight() {
Collection<StringNumber<BigDecimal>> expected = new Vector<StringNumber<BigDecimal>>();
expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));
Collection<StringNumber<BigDecimal>> actual = new Vector<StringNumber<BigDecimal>>();
expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));
//Collection<StringNumber<BigDecimal>> actual = A.f();
assertEquals(expected, actual);
}
但是正如您所看到的,即使集合中的元素相同,断言也会失败。可能是什么原因?
我得到的错误是
java.lang.AssertionError: expected: java.util.Vector<[a:1, b:1]> but was: java.util.Vector<[a:1, b:1]>
这对我来说并不有趣。
最佳答案
您的StringNumber
类需要equals()
方法。然后它就会起作用。假设此类包含 string
和 number
字段(由我的 IDE 自动生成):
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof StringNumber)) {
return false;
}
StringNumber that = (StringNumber) o;
if (number != null ? !number.equals(that.number) : that.number != null) {
return false;
}
return !(string != null ? !string.equals(that.string) : that.string != null);
}
@Override
public int hashCode() {
int result = string != null ? string.hashCode() : 0;
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
几点说明:
- 两个
vector
(为什么使用这种古老的数据结构)是相等的if :
both [...] have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements
e1
ande2
are equal if(e1==null ? e2==null : e1.equals(e2))
.)
这就是为什么需要重写equals()
。
- 实现
equals()
时,您必须实现hashCode()
。这里不需要,但安全总比后悔好:What issues should be considered when overriding equals and hashCode in Java? .
关于java - AssertEquals 与带有非原始模板参数的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112938/