JUnit assertEquals( ) fails for two objects

久未见 提交于 2019-11-28 23:05:05
Jon Skeet

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!