Terry Li
Terry Li

Reputation: 17268

JUnit assertEquals( ) fails for two objects

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?

Upvotes: 25

Views: 44516

Answers (3)

Ash
Ash

Reputation: 268

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 33

Binil Thomas
Binil Thomas

Reputation: 13779

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.

Upvotes: 2

Related Questions