try...catch 测试异常失败时,得到的提示:
无异常时:
java.lang.AssertionError: No exception thrown.
at org.junit.Assert.fail(Assert.java:91)
at cc.unmi.PasswordTest.passwordLengthLessThan6LettersThrowsException(PasswordTest.java:20)
异常类型不对或异常的 message 不对时:
java.lang.AssertionError:
at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.assertTrue(Assert.java:43)
at org.junit.Assert.assertTrue(Assert.java:54)
at cc.unmi.PasswordTest.passwordLengthLessThan6LettersThrowsException(PasswordTest.java:22)
上面能提供给我们的定位错误的帮助不是特别大
再看 @Test(expected=InvalidPasswordException.class) 时测试失败时的提示:
java.lang.AssertionError: Expected exception: cc.unmi.InvalidPasswordException
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:110)
用 @Rules ExpectedException方式来测试异常,失败时的提示:
java.lang.AssertionError:
Expected: (exception with message a string containing "YES. required" and an instance of java.lang.NullPointerException)
got:
at org.junit.Assert.assertThat(Assert.java:778)
at org.junit.Assert.assertThat(Assert.java:736)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:114)
特别是 @Rules ExpectedException 方法时为何测试失败提示的清清楚楚。期望什么异常,异常 message 中含何字符串,实际上确得到什么类型的异常,异常中 message 是什么。有了这,你一看到就知道怎么去修补你的程序。
所以到了这里,我们真的没理由不用 @Test(expected=...) 或 @Rule ExpectedException 的写法了。
22/2<12