Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;)

public class JW {
    private String name;
    private int quantityVoters;
    private int voted;

    public JW( String nam, int quantityV ) {
        if( nam == null || nam.length() == 0 || quantityV < 10 )
            throw new IllegalArgumentException( "JW: Wrong" );
        name= nam;
        quantityVoters= quantityV;
        voted= 0;
     }

    public void voting( int n ) {
        if( n < 0 || n > quantityVoters - voted )
            throw new IllegalArgumentException( "JW: soething wrong with voting!" );
        else
           voted += n;
    }

    public int novote() {
        return quantityVoters - voted;
    }

    public boolean equals( Object o ) {
        return o != null && o instanceof JW && ((JW)o).name.equals( name );
    }

    public int hashCode() {
        return name.hashCode();
    }

    public String toString() {
        return "JW " + name + ": quantity Voters: " + quantityVoters + ", voted: " + voted;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...