使用JUnit來測試Java代碼中的異常有很多種方式,你知道幾種?
給定這樣一個class。
Person.java
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 方式
@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"));
}
}