1
我想寫測試它檢查兩個對象是否相同。當斷言失敗時,我想知道哪些字段是相同的,哪些不是。我可以在每個領域做出斷言,但是想知道是否有辦法主持這些對象。如何使用hamcrest聲明對象相等
Truck類:
import java.util.List;
public class Truck {
private String model;
private String make;
private int year;
private List<TruckPartsObject> parts;
public Truck(String model, String make, int year) {
super();
this.model = model;
this.make = make;
this.year = year;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public List<TruckPartsObject> getParts() {
return parts;
}
public void setParts(List<TruckPartsObject> parts) {
this.parts = parts;
}
@Override
public String toString() {
return "Truck{" + "model='" + model + '\'' + ", make='" + make + '\''
+ ", year=" + year + ", parts=" + parts + '}';
}
}
TruckPartsObject類:
import java.util.HashMap;
public class TruckPartsObject {
private String name;
private String price;
private HashMap<String, String> partsHashMap;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public HashMap<String, String> getPartsHashMap() {
return partsHashMap;
}
public void setPartsHashMap(HashMap<String, String> partsHashMap) {
this.partsHashMap = partsHashMap;
}
@Override
public String toString() {
return "TruckPartsObject{" + "name='" + name + '\'' + ", price='"
+ price + '\'' + ", partsHashMap=" + partsHashMap + '}';
}
}
測試:
@Test
public void truckTest() {
Truck pickupTruck1 = new Truck("Big 10", "Chevy", 1976);
Truck pickupTruck2 = new Truck("Big 10", "Chevy", 1976);
List<TruckPartsObject> parts1 = new ArrayList<TruckPartsObject>();
TruckPartsObject truckPartsObject1 = new TruckPartsObject();
truckPartsObject1.setName("part1");
parts1.add(truckPartsObject1);
pickupTruck1.setParts(parts1);
List<TruckPartsObject> parts2 = new ArrayList<TruckPartsObject>();
TruckPartsObject truckPartsObject2 = new TruckPartsObject();
truckPartsObject2.setName("part1");
parts2.add(truckPartsObject2);
pickupTruck2.setParts(parts2);
pickupTruck2.setParts(parts2);
System.out.println(pickupTruck1);
System.out.println(pickupTruck2);
//how to assert pickupTruck1 and pickupTruck2 have the same
}
如何斷言pickupTruck1和pickupTruck2具有相同的?
'卡車'對象是否故意沒有'equals'方法,還是隻是沒有顯示在這裏? – Mureinik
它沒有等號方法。如果這是正確的解決方案,我可以添加equals方法。如果我這樣做,那麼我還必須重寫hasCode()並添加邏輯來檢查值是否爲空,並手動檢查每個值。此外,當測試失敗時,顯示實際與預期的錯誤消息將不會清晰。所以想知道是否有更好的解決方案。 –
您可以使用Apache commons-lang3庫的EqualsBuilder,HashCodeBuilder和ToStringBuilder。這將在發生故障時提供有用的錯誤消息。 –