[英]Strange behaviour of Assert.assertEquals
According to many posts here, Assert.assertEquals
should compare collections using deep insight, and two arrays of the same content should be equal. 根据此处的许多帖子,
Assert.assertEquals
应该使用深刻的洞察力比较集合,并且相同内容的两个数组应该相等。
I have JUnit 4.12 installed. 我已经安装了JUnit 4.12。
Calling 呼唤
List<Integer[]> result, targetResult;
(both are created as ArrayList)
....
Assert.assertEquals("counted small array ", result, targetResult);
, where result and targetResult have the same content, the test fails though. ,其中result和targetResult具有相同的内容,但是测试失败。
I have looked how the assertEquals
do the job. 我已经看过
assertEquals
如何完成这项工作。 For comparison of the Integer arrays it reached: 为了比较整数数组,它达到了:
//----in AbstractList:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator e2 = ((List) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
...
//and more deep, in Object:
public boolean equals(Object obj) {
return (this == obj);
}
And that means, that it compares simply references. 这意味着,它只比较引用。
How can I make Assert.assertEquals()
to work correctly? 如何使
Assert.assertEquals()
正常工作?
The problem with assertEquals is the assumption that the equals(Object)
is sane. assertEquals的问题在于
equals(Object)
是理智的假设。 Unfortunately, all arrays inherent from Object directly and have no specialised methods. 不幸的是,Object固有的所有数组都没有专门的方法。 This means that you have to call Arrays.equals(a, b) to compare two arrays, however if those arrays are inside a collection there is no way to do this conveniently.
这意味着您必须调用Arrays.equals(a,b)来比较两个数组,但是如果这些数组在集合内,则无法方便地执行此操作。
Note: I don't know why printing [Ljava.lang.Integer@72173fed
is a good toString
for such an array either (it is something I have ranted against in my blog more than once) 注意:我不知道为什么为这种数组打印
[Ljava.lang.Integer@72173fed
也是一个很好的toString
(这是我在博客中多次提出的建议)
And that means, that it compares simply hashcodes.
这意味着,它仅比较哈希码。
It doesn't compare hashCode()s, it compares references. 它不比较hashCode(),而是比较引用。 hashCode()s are not memory addresses, nor can they be as they cannot change when the object is moved in memory.
hashCode()既不是内存地址,也不是,因为当对象在内存中移动时它们无法更改。
If you want your data structures to be equal, use a collection which supports equals as you expect 如果您希望数据结构相等,请使用符合您期望的支持相等的集合
List<List<Integer>> result
if you you want efficiency as int
use 4 bytes and Integer
can use 20 bytes including it's reference. 如果您想要效率,因为
int
使用4个字节,而Integer
可以使用20个字节(包括引用)。
List<int[]> result
public static void assertEqualsArray(List<Int[]> a, List<int[]> b) {
// compare the list of arrays.
}
考虑:
Assert.assertArrayEquals(result.toArray(), targetResult.toArray());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.