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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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:
public boolean equals(MyClass other)
where you should have:
@Override // Force the compiler to check I'm really overriding something
public boolean equals(Object other)
In your working assertion, you were no doubt calling the overloaded method as the compile-time type of obj1
and obj2
were both MyClass
(or whatever your class is called). JUnit's assertEquals
will only call equals(Object)
as it doesn't know any better.
回答2:
Here is the code for assertEquals
(from Github):
static public void assertEquals(String message, Object expected,
Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && isEquals(expected, actual))
return;
else if (expected instanceof String && actual instanceof String) {
String cleanMessage= message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, (String) expected,
(String) actual);
} else
failNotEquals(message, expected, actual);
}
private static boolean isEquals(Object expected, Object actual) {
return expected.equals(actual);
}
I can think of only one case where this behaves the way you described - if your equals
method is not handling comparisons to null
values correctly.