junit中对异常测试的小结总结

junit中对异常测试的小结总结,有如下几种方法:

假设有如下的类
public class Person {
  private final String name;
  private final int age;

  /**
   * Creates a person with the specified name and age.
   *
   * @param name the name
   * @param age the age
   * @throws IllegalArgumentException if the age is not greater than zero
   */
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
    if (age <= 0) {
      throw new IllegalArgumentException('Invalid age:' + age);
    }
  }
}


要进行测试,方法1:
   使用 ExpectedException :
 
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);
  }
}

   这种方法,可以指定异常的消息:


2)使用@Test注解
  
@Test(expected = IllegalArgumentException.class)
public void testExpectedException2() {
  new Person('Joe', -1);
}

    这种方法不能指定断言的异常信息

3) try-catch
  

@Test
public void testExpectedException3() {
  try {
    new Person('Joe', -1);
    fail('Should have thrown an IllegalArgumentException because age is invalid!');
  } catch (IllegalArgumentException e) {
    assertThat(e.getMessage(), containsString('Invalid age'));
  }
}

你可能感兴趣的:(JUnit)