简体   繁体   English

我的JUnit测试失败

[英]My JUnit Test Fails

Why does this fail the JUnit Test. 为什么这会使JUnit测试失败。 I have a class called Complex for Complex Numbers with the Constructor accepting 2 parameters real and imaginary which looks like this 我有一个名为Complex for Complex Numbers的类,构造函数接受2个实数和虚数参数,如下所示

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 然后我有一种添加方法,称为add

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. 如果输入正确的参数,则JUnit测试应该通过。 Where am I going wrong? 我要去哪里错了?

myComplex.add(other) returns an object reference. myComplex.add(other)返回一个对象引用。 newComplex is also an object reference, which refers to another object. newComplex还是一个对象引用,它引用另一个对象。 So when you say myComplex.add(other) == newComplex you are trying to check if the two references are the same, which is not. 因此,当您说myComplex.add(other) == newComplex您正在尝试检查两个引用是否相同, myComplex.add(other) == newComplex并非如此。

If you want to compare the two objects, you need to override equals() and hashCode() methods from the base class Object . 如果要比较两个对象,则需要从基类Object重写equals()hashCode()方法。 Refer to this question to find out how to do that. 请参阅此问题以了解如何执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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