testEquals(), testHashCode() and testToString()

前端 未结 2 1616
攒了一身酷
攒了一身酷 2020-12-12 08:17

I prepared short Java class. Could anyone show me how write voids: testEquals, testHashCode, testToString for this code in junit? I have a little problem with it;)



        
2条回答
  •  春和景丽
    2020-12-12 08:45

    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.

提交回复
热议问题