Junit中测试异常的⽅法Java中测试异常的⽅式有很多种,下⾯介绍⼏种使⽤JUnit来测试Java代码中的异常
⾸先创建⼀个Person类代码如下:
public class Person {
private final int age;
private final String name;
public Person(int age, String name)throws IllegalAgeException {
super();
if(age <0)
throw new IllegalAgeException("年龄不合法");
this.age = age;
this.name = name;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
}
⾃定义⼀个异常类如下:当年龄不合法时抛出此异常
public class IllegalAgeException  extends Exception{
public IllegalAgeException(){super();}
public IllegalAgeException(String message){super(message);}
}
下⾯通过Junit来测试异常是否抛出
第⼀种⽅法:使⽤try-fail-catch⽅式来测试异常
@Test
public void testAge()throws IllegalAgeException {
try{
Person p =new Person(-1,"lihua");
fail("Expected an IllegalAgeException to be thrown");
}catch(IllegalAgeException e){
Message().equals("年龄不合法"));
}
}
测试结果如下:
这种⽅法⽐较容易想到,但是⽤起来⽐较繁琐。
第⼆种⽅法:JUnit annotation⽅式
JUnit中提供了⼀个expected的annotation来检查异常,
使⽤⽅法如下:
public class testPerson {
@Test(expected = IllegalAgeException.class)
public void testAge()throws IllegalAgeException {
Person p =new Person(-1,"lihua");
}
}
测试运⾏结果如下:
这种⽅式虽然⽤起来要简洁多了,但是⽆法检查异常中的消息。第三种⽅法:ExpectedException rule
JUnit5以后提供了⼀个叫做ExpectedException的Rule来实现对异常的测试。  使⽤⽅法如下:
public class testPerson {
@Rule
public ExpectedException exception = ();
@Test
public void testAge()throws IllegalAgeException {
Person p =new Person(-1,"lihua");
}
}
测试结果如下:
这种⽅式既可以检查异常类型,也可以验证异常中的消息,⽽且⽤起来也⽐较简洁。
>try catch的使用方法

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。