Reputation: 19
Why does this fail the JUnit Test. I have a class called Complex for Complex Numbers with the Constructor accepting 2 parameters real and imaginary which looks like this
Public Complex(double real, double imaginary) {
this.real=real;
this.imagine=imagine;
}
And then I have a method for adding to it called add like this
Public Complex add (Complex other) {
double temporaryReal = real + other.real;
double temporaryImagine = Imagine + other.Imagine;
return new Complex(temporaryReal, tempImagine);
}
I have a test class set up for testing the method. It looks like this
public void testAdd() {
Complex other = new Complex(15, 30);
Complex newComplex = new Complex(15, 30);
assertTrue( myComplex.add(other) == newComplex );
}
If I put in the correct parameters, the JUnit test should pass. Where am I going wrong?
Upvotes: 0
Views: 94
Reputation: 1756
myComplex.add(other)
returns an object reference. newComplex
is also an object reference, which refers to another object. So when you say myComplex.add(other) == newComplex
you are trying to check if the two references are the same, which is not.
If you want to compare the two objects, you need to override equals()
and hashCode()
methods from the base class Object
. Refer to this question to find out how to do that.
Upvotes: 2