JUnit assertEquals( ) fails for two objects

2019-01-23 02:20发布

问题:

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.



标签: junit equals