JUnit AssertEquals 失败
JUnit AssertEquals fails
我有一个代码用于以下内容
import static org.junit.Assert.assertEquals;
System.out.println("obj1 name = " + obj1.getName());
System.out.println("obj1 value = " + (obj1.getvalue() == null ? "null" : "not null"));
System.out.println("obj2 name = " + obj2.getName());
System.out.println("obj2 value = " + (obj2.getvalue() == null ? "null" : "not null"));
assertEquals(obj2, obj1);
产量
obj1 name = DC2
obj1 value = null
obj2 name = DC2
obj2 value = null
java.lang.AssertionError:
Expected :com.gms.contract.myClass.inventory.MyClass@795ce9b5
Actual :com.gms.contract.myClass.inventory.MyClass@280cb0b4
assertEquals不是应该按值比较吗??
在我看来,它比较对象地址。
但也许我错了?...
Isn't assertEquals suppose to compare by value??
不是,应该用equals
的方法比较。
您需要在 MyClass
中覆盖 equals
(并相应地覆盖 hashCode
)。
It looks to me that it compares objects address.
不,这只是在 MyClass
上调用 toString()
的结果,您没有覆盖它。如果您希望显示更有意义的内容,请也覆盖 toString()
。
我有一个代码用于以下内容
import static org.junit.Assert.assertEquals;
System.out.println("obj1 name = " + obj1.getName());
System.out.println("obj1 value = " + (obj1.getvalue() == null ? "null" : "not null"));
System.out.println("obj2 name = " + obj2.getName());
System.out.println("obj2 value = " + (obj2.getvalue() == null ? "null" : "not null"));
assertEquals(obj2, obj1);
产量
obj1 name = DC2
obj1 value = null
obj2 name = DC2
obj2 value = null
java.lang.AssertionError:
Expected :com.gms.contract.myClass.inventory.MyClass@795ce9b5
Actual :com.gms.contract.myClass.inventory.MyClass@280cb0b4
assertEquals不是应该按值比较吗?? 在我看来,它比较对象地址。 但也许我错了?...
Isn't assertEquals suppose to compare by value??
不是,应该用equals
的方法比较。
您需要在 MyClass
中覆盖 equals
(并相应地覆盖 hashCode
)。
It looks to me that it compares objects address.
不,这只是在 MyClass
上调用 toString()
的结果,您没有覆盖它。如果您希望显示更有意义的内容,请也覆盖 toString()
。