eclipse
*先放源码:实体类: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;}}测试:public class abc {@Testpublic void aaa(){Person person = new Person();person.setAge(-1);}}
*1.try…catch…finally方式public class abc {@Testpublic void aaa(){Person person = new Person();try {person.setAge(-1);} catch (Exception e) {} }}
*2.hrows抛异常public class abc {@Testpublic void aaa() throws Exception{FileInputStream fis = new FileInputStream('xxx.txt');fis.close();}}
*3.junit annotation方式 JUnit中提供了一个expected的annotation来检查异常。@Test(expected = IllegalArgumentException.class) public void shouldGetExceptionWhenAgeLessThan0() { Person person = new Person(); person.setAge(-1); }这种方式看起来要简洁多了,但是无法检查异常中的消息。
*4.ExpectedException方式 JUnit7以后提供了一个叫做ExpectedException的Rule来实现对异常的测试。 @Rule public ExpectedException exception = ExpectedException.none(); @Test public void shouldGetExceptionWhenAgeLessThan0() { Person person = new Person(); exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString('age is invalid')); person.setAge(-1); }这种方式既可以检查异常类型,也可以验证异常中的消息。
*5.catch-exception库 有个catch-exception库也可以实现对异常的测试。 首先引用该库。pom.xml