[英]My JUnit Test Fails
為什么這會使JUnit測試失敗。 我有一個名為Complex for Complex Numbers的類,構造函數接受2個實數和虛數參數,如下所示
Public Complex(double real, double imaginary) {
this.real=real;
this.imagine=imagine;
}
然后我有一種添加方法,稱為add
Public Complex add (Complex other) {
double temporaryReal = real + other.real;
double temporaryImagine = Imagine + other.Imagine;
return new Complex(temporaryReal, tempImagine);
}
我設置了一個測試類來測試該方法。 看起來像這樣
public void testAdd() {
Complex other = new Complex(15, 30);
Complex newComplex = new Complex(15, 30);
assertTrue( myComplex.add(other) == newComplex );
}
如果輸入正確的參數,則JUnit測試應該通過。 我要去哪里錯了?
myComplex.add(other)
返回一個對象引用。 newComplex
還是一個對象引用,它引用另一個對象。 因此,當您說myComplex.add(other) == newComplex
您正在嘗試檢查兩個引用是否相同, myComplex.add(other) == newComplex
並非如此。
如果要比較兩個對象,則需要從基類Object
重寫equals()
和hashCode()
方法。 請參閱此問題以了解如何執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.