testEquals(), testHashCode() and testToString()

前端 未结 2 1609
攒了一身酷
攒了一身酷 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:35

    I would advise against using those names for your tests. Each test case should assert JUST ONE thing about the behaviour of your class. So, you might have test cases called -

    • equalsReturnsTrueForJWWithSameName()
    • equalsReturnsFalseForJWWithDifferentName()
    • equalsReturnsTrueForSameObject()
    • equalsReturnsFalseForObjectThatIsntJW()
    • hashCodeReturnsSameValueForJWObjectsWithSameName()
    • toStringReturnsStringWithNameAndNumberOfVotersAndNumberVoted()

    So, for example, the first and last methods here might look like this.

    @Test
    public void equalsReturnsTrueForJWWithSameName(){
       JW toTest = new JW( "Fred", 5 );
       JW other = new JW( "Fred", 10 );
       assertTrue( toTest.equals( other ));
    }
    
    @Test
    public void toStringReturnsStringWithNameAndNumberOfVotersAndNumberVoted(){
       JW toTest = new JW( "Fred", 5 );
       toTest.voting( 2 );
       String expected = "JW Fred: quantity Voters: 5, voted: 2";
       assertEquals( expected, toTest.toString());
    }
    

    The other methods will follow a similar pattern. Try to make sure that each test only has one assertion in it. Feel free to post again if you get stuck; I don't mind providing more help.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题