junit 4中对指定错误的测试

junit 4中对指定异常的测试
junit 4中,也可以测试指定的异常是否出现了,比如:


public class Person {
  private final String name;
  private final int age;

  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
    if (age <= 0) {
      throw new IllegalArgumentException('Invalid age:' + age);
    }
  }
}


  要测试是否IllegalArgumentException抛出了,则可以使用注解的annotation:


import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class PersonTest {

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void testExpectedException() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage(containsString('Invalid age'));
    new Person('Joe', -1);
  }
}


但很奇怪,居然不能这样:
@Test(expected = IllegalArgumentException.class)
public void testExpectedException2() {
  new Person('Joe', -1);
}