[英]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.