Question

Why is the following code giving me an error, I'm so confused.

@Test
public void testUsers()
{
    User user1 = new User("a");
    User user2 = new User("a");
    assertSame(user1, user2);
}

This is the error I am receiving at the moment:

expected same:<xxx.xxx.User@615fd9fd> was not:<xxx.xxx.User@5be0a2fc>
java.lang.AssertionError

I understand they are difference instances of the same object, but why this error?

Was it helpful?

Solution

The source code for assertSame() is this:

static public void assertSame(Object expected, Object actual) {
    assertSame(null, expected, actual);
}

static public void assertSame(String message, Object expected, Object actual) {
    if (expected == actual) {
        return;
    }
    failNotSame(message, expected, actual);
}

So assertSame() is testing that the provided references point to the exact same object, which in your case they are not.

What you want is probably assertEquals():

static public void assertEquals(String message, Object expected,
        Object actual) {
    if (equalsRegardingNull(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 equalsRegardingNull(Object expected, Object actual) {
    if (expected == null) {
        return actual == null;
    }

    return isEquals(expected, actual);
}

private static boolean isEquals(Object expected, Object actual) {
    return expected.equals(actual);
}

OTHER TIPS

You have to implement the equals() and hashCode() on the User object...most of IDEs help you generate it correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top