检查 Java JUnit 中 ArrayList 内容的相等性

Checking equality of ArrayList's content in Java JUnit

我在 JUnit 测试中检查两个数组列表是否相等时遇到问题。当我测试两个列表是否相等时,它只检查它们的字符串表示是否相同。它适用于简单示例,例如 [1,2,3]、[1,2,3],或者当列表包含以字符串表示的对象及其所有属性时。但是当我有两个具有相同字符串表示形式但某些对象具有不同属性的列表时,我该如何检查它们是否相等?

这是例子:

如果我有 Class 人的对象(int height, int weight, boolean alive),并且 toString() 方法是:

   public static String toString() {
        return this.height + "-" + this.weight;
   }

我有两个列表 [20-30] 和 [20-30] 但第一个对象有

 boolean alive = false 

第二个

 boolean alive = true

如何告诉编译器列表不相等?抱歉混淆解释,提前谢谢你!!! :D

您可以使用 Assert.class

 assertArrayEquals(Object[] expecteds, Object[] actuals) 

http://junit.org/junit4/javadoc/4.8/org/junit/Assert.html

您的对象的 equals 方法必须比较所有必要的属性。

您需要重写 hashcode 和 equals 方法。这是代码

输出为

正确 假

public class test {
    public static void main(String[] args) {
        Human rob = new Human(110, 100, false);
        Human bob = new Human(110, 100, true);
        Human tob = new Human(110, 100, false);
        System.out.println(rob.equals(tob));
        System.out.println(rob.equals(bob));
    }
}

class Human {
    int height;
    int weight;
    boolean alive;

    public Human(int height, int weight, boolean alive) {
        super();
        this.height = height;
        this.weight = weight;
        this.alive = alive;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (alive ? 1231 : 1237);
        result = prime * result + height;
        result = prime * result + weight;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Human other = (Human) obj;
        if (alive != other.alive)
            return false;
        if (height != other.height)
            return false;
        if (weight != other.weight)
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Human [height=" + height + ", weight=" + weight + "]";
    }
}

比较列表的(恕我直言)最易读的方法:

assertThat(actualitems, is(expectedItems));

使用 assertThat() 和 hamcrest is() 匹配器(参见 here 进一步阅读)。

为了实现这一点:您必须在 class 上实施 equals()(因此 hashCode()(请参阅 here 了解如何做到这一点).

换句话说:如果您希望此类字段在比较两个对象时采用 part,那么 you 需要通过"field by field" @Override equals() 实现的比较部分。任何体面的IDE都可以为你生成那些方法——但是在学习Java的时候,自己做几次是很好的练习。

一个简单的方法是

assertTrue("check equality", Arrays.equals(list1.toArray(), list2.toArray());

唯一的缺点是您只能得到它们不相等的信息,而不知道数组中不相等发生的位置。