Java中测试异常的多种方式(3)
发表于:2014-04-14来源:博客园作者:黄博文点击数:
标签:软件测试
然后这样书写测试。 1 2 3 4 5 6 7 8 @Test public void shouldGetExceptionWhenAgeLessThan0 () { Person person = new Person (); catchException ( person ). setAge (- 1 ); assertThat ( caughtExcept
然后这样书写测试。
1
2
3
4
5
6
7
8
|
@Test
public void shouldGetExceptionWhenAgeLessThan0() {
Person person = new Person();
catchException(person).setAge(-1);
assertThat(caughtException(),instanceOf(IllegalArgumentException.class));
assertThat(caughtException().getMessage(), containsString("age is invalid"));
}
|
这样的好处是可以精准的验证异常是被测方法抛出来的,而不是其它方法抛出来的。
catch-exception库还提供了多种API来进行测试。
先加载fest-assertion库。
1
2
3
4
5
|
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<version>2.0M10</version>
</dependency>
|
然后可以书写BDD风格的测试。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@Test
public void shouldGetExceptionWhenAgeLessThan0() {
// given
Person person = new Person();
// when
when(person).setAge(-1);
// then
then(caughtException())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("age is invalid")
.hasNoCause();
}
|
原文转自:http://www.cnblogs.com/huang0925/p/3663074.html