假如需要测试下面的类:
public class Student {
public boolean canVote(int age) {
if (i<=0) throw new IllegalArgumentException("age should be +");
if (i<18) return false;
else return true;
测试抛出的异常有三种方法:
@Test ( expected = Throwable.class )
@Test(expected = IllegalArgumentException.class)
public void canVoteExp() {
Student student = new Student();
student.canVote(0);
这种测试有一点误差,因为异常会在方法的某个位置被抛出,但不一定在特定的某行。
ExpectedException
如果要使用JUnit框架中的ExpectedException类,需要声明ExpectedException异常。
@Rule
public ExpectedException thrown = ExpectedException.none();
然后可以使用更加简单的方式验证预期的异常
@Test
public void canVoteExp() {
Student student = new Student();
thrown.expect(IllegalArgumentException.class);
student.canVote(0);
还可以设置预期异常的属性信息
@Test
public void canVoteExp() {
Student student = new Student();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("age should be +");
student.canVote(0);
这种方法可以更加精确的找到异常抛出的位置。
try/catch with assert/fail
在JUnit4之前的版本中,使用try/catch语句块检查异常
@Test
public void canVoteExp() {
Student student = new Student();
try {
student.canVote(0);
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("age should be +"));