JUnitassertEquals() 对于两个对象失败
我创建了一个类并重写了 equals() 方法。当我使用assertTrue(obj1.equals(obj2))时,它会通过测试;但是,assertEquals(obj1, obj2)
将无法通过测试。有人可以告诉一下原因吗?
I created a class and overridden the equals() method. When I use assertTrue(obj1.equals(obj2))
, it will pass the test; however, assertEquals(obj1, obj2)
will fail the test. Could someone please tell the reason why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的猜测是,您实际上并没有覆盖
equals
- 您已经重载了它。使用 @Override 注释可以在编译时找到此类内容。换句话说,我怀疑您已经:
您应该在哪里:
在您的工作断言中,您无疑将重载方法调用为 obj1 和 obj2< 的编译时类型/code> 都是
MyClass
(或者你的类的名称)。 JUnit 的assertEquals
只会调用equals(Object)
,因为它不知道更多。My guess is that you haven't actually overridden
equals
- that you've overloaded it instead. Use the@Override
annotation to find this sort of thing out at compile time.In other words, I suspect you've got:
where you should have:
In your working assertion, you were no doubt calling the overloaded method as the compile-time type of
obj1
andobj2
were bothMyClass
(or whatever your class is called). JUnit'sassertEquals
will only callequals(Object)
as it doesn't know any better.这是
assertEquals
的代码(来自 Github):我只能想到一种情况,其行为如您所描述的方式 - 如果您的
equals
方法不处理与null 的比较
值正确。Here is the code for
assertEquals
(from Github):I can think of only one case where this behaves the way you described - if your
equals
method is not handling comparisons tonull
values correctly.正如其他人提到的,您需要重写 equals() 函数。如果您使用某些 IDE,那么这会容易得多。例如,在 Eclipse 中,在您的 java 文件中,右键单击 ->来源->生成hashCode()和equals(),就可以了。再次运行测试,现在应该可以通过。
生成这些方法也是一个很好的做法,因为它们有自己的优点,这将使您的代码更强大并使其更符合 OOAD 原则。
As others have mentioned, you need to override the equals() function. It's a lot easier to do if you're using some IDE. For instance, in eclipse, in your java file, right click -> source -> Generate hashCode() and equals(), will do it. Run the tests again and it should pass now.
It is also a good practice to generate these methods as they have their own advantages which will make your code stronger and make it comply to the OOAD principals more.