1
屬性例如:檢查兩個對象是相同的,根據它們在Java
public class Fruit{
private String color;
private double weight;
...
public boolean equals(Fruit a){
return (this.getColor().equals(a.getColor()) && (this.getWeight()==a.getWeight()));
}
}
public class Orange extends Fruit{
public Orange(double weight) {
super("orange", weight);
}
}
public class NavalOrange extends Orange{
public NavalOrange(double weight) {
super(weight);
}
}
然後我寫了一個關於這個測試來檢查兩個對象,如果它們是相同的。
Orange orange = new Orange(8);
NavalOrange navalOrange = new NavalOrange(8);
assertEquals(orange, navalOrange);
但它只是不斷返回錯誤:
junit.framework.AssertionFailedError: expected:<[email protected]> but was:<[email protected]>
任何人都可以解釋爲什麼這是怎麼回事?我認爲在toString
方法中可能會出現問題。
Your equals must take a object as a parameter;如果你需要水果,jUnit不會找到它。如果您使用的是Eclipse,請嘗試右鍵單擊Fruit類並選擇Generate equals()和hashcode()。 – Pokechu22 2014-10-20 01:07:41