Re: Problem with Junit test
djgavenda2@yahoo.com wrote:
I am running into a problem when two objects return true for .equals()
and return the same exact hashcode but assertEquals throws
AssertionFailedErrorException.
Since they return true for .equals and hashcode is exactly the same, I
am confused why assertEquals barks.
Any ideas?
no idea, thie follow simple test shows assertEquals works ok .
package com.amd.sandbox;
import junit.framework.TestCase;
public class EqualsTest extends TestCase {
public void testEqualsWhereHashcodeIsSameAndEqualsReturnsTrue() {
Foo f1 = new Foo("hello");
Foo f2 = new Foo("hello");
assertEquals("failed!", f1, f2);
assertEquals("Hashcode differs!", f1.hashCode(), f2.hashCode());
}
public void testNotEqualWhenMessageDifferent() {
Foo f1 = new Foo("hello");
Foo f2 = new Foo("bye");
assertFalse("failed!", f1.equals(f2));
assertFalse("Hashcode the same!", f1.hashCode() == f2.hashCode());
}
private static class Foo {
private String message;
public Foo(String aMessage) {
message = aMessage;
}
public boolean equals(Object obj) {
Foo other = (Foo) obj;
if (this.message.equals(other.message))
return true;
return false;
}
public int hashCode() {
return message.hashCode();
}
}
}