testEquals(),testHashCode()和testToString()

我准备了简短的Java类。 任何人都可以告诉我如何写junoid:testEquals,testHashCode,testToString这个代码在junit? 我有点问题;)

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

开始的小例子:

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

关于equalshashCode ,他们必须遵循某个合同。 简而言之:如果实例相等,它们必须返回相同的hashCode(但相反的情况不一定如此)。 您可能也想为此编写断言,例如通过重载assertEquals以断言如果对象相等则hashCode相等:

  private static void assertEquals(String name, JW one, JW two){ assertEquals(name, (Object)one, (Object)two); assertEquals(name + "(hashcode)", one.hashCode(), two.hashCode()); } 

toString没有特殊的合同,只要确保它永远不会抛出exception,或者需要很长时间。

我建议不要在测试中使用这些名称。 每个测试用例都应该断言你class级的行为。 所以,你可能有测试用例 –

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

因此,例如,这里的第一个和最后一个方法可能如下所示。

 @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()); } 

其他方法将遵循类似的模式。 尝试确保每个测试只有一个断言。 如果你遇到困难,请随时再发帖; 我不介意提供更多帮助。