使用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"));
}
}