Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - testEquals(), testHashCode() and testToString()

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...