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?

2
  • 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... Commented Apr 20, 2018 at 3:18
  • This seems to have many problems with variable declarations and initializations. Specially with cases.. Commented Apr 20, 2018 at 3:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.