Java中測試異常的多種方式
發表于:2014-04-14來源:博客園作者:黃博文點擊數:
標簽:軟件測試
Java中測試異常的多種方式 使用JUnit來測試Java代碼中的異常有很多種方式,你知道幾種?
使用JUnit來測試Java代碼中的異常有很多種方式,你知道幾種?
給定這樣一個class。
Person.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0 ) {
throw new IllegalArgumentException("age is invalid");
}
this.age = age;
}
}
|
我們來測試setAge方法。
Try-catch 方式
1
2
3
4
5
6
7
8
9
10
11
|
@Test
public void shouldGetExceptionWhenAgeLessThan0() {
Person person = new Person();
try {
person.setAge(-1);
fail("should get IllegalArgumentException");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(),containsString("age is invalid"));
}
}
|
原文轉自:http://www.cnblogs.com/huang0925/p/3663074.html