2013-04-10 51 views
0

我正在写很多单元测试,但是用不同的类来做类似的事情。Java:两套选择性比较

我想比较相同类的集合。该类指定一个id属性。在集合A中,这个属性全为空。在集合B中,该属性已设置。 (集B已被持久化到数据库并且已经填充了uid)。

对于我的单元测试,我想确保Set A与Set B匹配,我显然不希望它看到id字段。

这样做最有效,干净和干燥的方式是什么?

+1

说真的,人们有什么关闭/倒票?也许这不是一个完美的问题,但首先要求这个人增加/改写而不是抨击。 – MaDa 2013-04-10 10:55:48

回答

1

首先,比较两套尺寸,如果不相等,则测试失败。

对于非平凡的情况,为集合元素定义了一个java.util.Comparator,根据此比较器对两者进行排序(可以包含/省略您不想比较的属性)。然后迭代两个集合,根据您的规则比较元素(如果我正确理解您的观点,则与比较器定义的元素不同)。

我假设你已经有你的equalshashCode方法正确定义,不想为了测试而改变它们。

+0

我选择了这个答案,因为MaDa在他们的假设中非常正确,我不想为了测试而改变被测试的类(即定义不同的equals和hashCode方法) – 2014-04-25 13:02:57

0

您需要重写类的hashCode()和equals()方法,您不应该在方法中包含id字段,那么equals方法Set将会以您想要的方式工作。

例如

class Test{ 

int id; 
String name; 
String other; 
@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + ((name == null) ? 0 : name.hashCode()); 
    result = prime * result + ((other == null) ? 0 : other.hashCode()); 
    return result; 
} 
@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    Test other = (Test) obj; 
    if (name == null) { 
     if (other.name != null) 
      return false; 
    } else if (!name.equals(other.name)) 
     return false; 
    if (this.other == null) { 
     if (other.other != null) 
      return false; 
    } else if (!this.other.equals(other.other)) 
     return false; 
    return true; 
} 

}

现在Test类对象不依赖于ID。你可以很容易地使用Eclipse等IDE来生成equlas和hashCode方法。

0

您可以覆盖类的equals() & hashCode()方法,然后用removeAll()方法从Set B删除所有元素。发布这个,如果这个集合是空的,那么它们匹配,否则它们不匹配。

请注意,重写的方法应该有逻辑,其中不涉及id

0

比较重复项目的逻辑是用Java实现的,使用等于()方法。

myString.equals(“compare this”);

当您需要比较自定义类型的对象时,必须重写equals方法。

Student student1=new Student(); 
Student student2=new Student(); 
student1.equals(student2); 

但是在覆盖equals()方法时要小心。您需要根据一些独特的ID提供一些比较基础。例如,以下实施方式使用卷号作为唯一的ID进行比较

public class Student { 

    private int rollNo; 
    private String name; 
    private String address; 


    // Getters and Setters 

@Override 
    public int hashCode() { 
    // Overide this only when you use Hashing implementations 
    } 

    @Override 
    public boolean equals(Object obj) { 
    if (obj == null) { 
     System.out.println("Not Equal due to NULL"); 
     return false; 
    } 
    if (this == obj) { 
     System.out.println("Equals due to same reference"); 
     return true; 
    } 
    if (getClass() != obj.getClass()) { 
     System.out.println("Different Type"); 
     return false; 
    } 
    Student other = (Student) obj; 
    if (rollNo == other.rollNo) { 
     System.out.println("RollNo " + rollNo + " EQUALS " + other.rollNo); 
     return true; 
    } 
    if (rollNo != other.rollNo) { 
     System.out.println("RollNo " + rollNo + " NOT EQUALS " + other.rollNo); 
     return false; 
    } 
    System.out.println("Default is FALSE"); 
    return false; 
    } 

}