Small example to get you started:
public class JWTest extends TestCase {
public void testEquals(){
JW one = new JW("one", 10);
JW two = new JW("two", 10);
assertFalse("nullsafe", one.equals(null));
assertFalse("wrong class", one.equals(1234));
assertEquals("identity", one, one);
assertEquals("same name", one, new JW("one", 25));
assertFalse("different name", one.equals(two));
}
}
With regards to equals
and hashCode
, they have to follow a certain contract.
In a nutshell: If instances are equal, they must return the same hashCode (but the opposite is not necessarily true). You may want to write assertions for that as well, for example by overloading assertEquals to also assert that the hashCode is equal if the objects are equal:
private static void assertEquals(String name, JW one, JW two){
assertEquals(name, (Object)one, (Object)two);
assertEquals(name + "(hashcode)", one.hashCode(), two.hashCode());
}
There is no special contract for toString
, just make sure that it never throws exceptions, or takes a long time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…