简体   繁体   中英

My JUnit Test Fails

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM