我正在寫很多單元測試,但是用不同的類來做類似的事情。Java:兩套選擇性比較
我想比較相同類的集合。該類指定一個id屬性。在集合A中,這個屬性全爲空。在集合B中,該屬性已設置。 (集B已被持久化到數據庫並且已經填充了uid)。
對於我的單元測試,我想確保Set A與Set B匹配,我顯然不希望它看到id字段。
這樣做最有效,乾淨和乾燥的方式是什麼?
我正在寫很多單元測試,但是用不同的類來做類似的事情。Java:兩套選擇性比較
我想比較相同類的集合。該類指定一個id屬性。在集合A中,這個屬性全爲空。在集合B中,該屬性已設置。 (集B已被持久化到數據庫並且已經填充了uid)。
對於我的單元測試,我想確保Set A與Set B匹配,我顯然不希望它看到id字段。
這樣做最有效,乾淨和乾燥的方式是什麼?
首先,比較兩套尺寸,如果不相等,則測試失敗。
對於非平凡的情況,爲集合元素定義了一個java.util.Comparator
,根據此比較器對兩者進行排序(可以包含/省略您不想比較的屬性)。然後迭代兩個集合,根據您的規則比較元素(如果我正確理解您的觀點,則與比較器定義的元素不同)。
我假設你已經有你的equals
和hashCode
方法正確定義,不想爲了測試而改變它們。
我選擇了這個答案,因爲MaDa在他們的假設中非常正確,我不想爲了測試而改變被測試的類(即定義不同的equals和hashCode方法) – 2014-04-25 13:02:57
您需要重寫類的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方法。
您可以覆蓋類的equals()
& hashCode()
方法,然後用removeAll()
方法從Set B
刪除所有元素。發佈這個,如果這個集合是空的,那麼它們匹配,否則它們不匹配。
請注意,重寫的方法應該有邏輯,其中不涉及id
。
比較重複項目的邏輯是用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;
}
}
說真的,人們有什麼關閉/倒票?也許這不是一個完美的問題,但首先要求這個人增加/改寫而不是抨擊。 – MaDa 2013-04-10 10:55:48