测试可能会抛出IllegalArgumentException异常的方法,使用哪种断言方法比较好
用异常状态断言
llegalState
/**
* Assert a boolean expression, throwing <code>IllegalStateException</code>
* if the test result is <code>false</code>. Call isTrue if you wish to
* throw IllegalArgumentException on an assertion failure.
* <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre>
* @param expression a boolean expression
* @param message the exception message to use if the assertion fails
* @throws IllegalStateException if expression is <code>false</code>
*/
public static void state(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
catch-exception库可实现对异常的test,
类似:assertThat(caughtException(),instanceOf(IllegalArgumentException.class));
好处是可以验证异常是被测方法抛出的,而不是其它方法抛出的。
需要先加下如下依赖catch-exception库
<!-- https://mvnrepository.com/artifact/com.googlecode.catch-exception/catch-exception -->
<dependency>
<groupId>com.googlecode.catch-exception</groupId>
<artifactId>catch-exception</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>