JUnit assertEquals( ) fails for two objects

送分小仙女□ 提交于 2019-11-27 14:30:49

问题


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.



来源:https://stackoverflow.com/questions/6060848/junit-assertequals-fails-for-two-objects

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