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