I've been fighting what should be a simple unit test for too long and
would appreciate some guidance please :) I've whittled it down to the
following code,
@Test
public void testStringBuffer() {
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
assertEquals(sb1, sb2);
}
Given this, JUnit reports tells me:
java.lang.AssertionError: expected: java.lang.StringBuilder<> but was:
java.lang.StringBuilder<>
Si
StringBuffer doesn't override the equals(Object o) method from the
Object class.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
The Object implementation of equals returns true when the object and
the argument refer to the same object instance. That means that if sb1
and sb2 are references to StringBuffer instances, if you call
sb1.equals(sb2) it will never return true unless sb1 and sb2 refer to
the same StringBuffer instance.
That's why your test is failing - they are not referring to the same
object. The confusing error message? Dunno, I would expect just a
JUnit thing.
Cheers
@Paul - Makes sense now, I was comparing two resource handles/
references rather than the contents of the buffer.
So to make it work I need:
assertEquals(sb1.toString(), sb2toString());
Cheers,
Si
Probably no need to but it confused me at first, so I'll just stress
that it *coulda* returned true... if StringBuffer had overridden the
equals method to do so.
Worth knowing how equals, hashCode and == work, can help you avoid
confusing results later particularly with hash based collections like
HashMap and HashSet. Maybe start on developerworks
http://www.ibm.com/developerworks/library/j-jtp05273.html
Cheers
Aye, it's beside me now. It's not quite what I was expecting tbh, but
it's good so far :)