0

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?

Joshua
  • 19
  • 1
  • 3
  • is `Imagine` spelled with uppercase `I` when you add? and in the constructor you pass `imaginary` but the variable is `imagine`. And what is `myComplex`? unless it is zero your assert will be false. And comparison of objects is not done with `==`. So many potential problems here... – tima Apr 20 '18 at 03:18
  • This seems to have many problems with variable declarations and initializations. Specially with cases.. – Romeo Sierra Apr 20 '18 at 03:22

1 Answers1

2

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.

Romeo Sierra
  • 1,666
  • 1
  • 17
  • 35