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(
·
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) {
assertTrue(e.getMessage().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 = ExpectedException.none();
@Test
public void testAge() throws IllegalAgeException {
exception.expect(IllegalAgeException.class);
exception.expectMessage("年龄不合法");
Person p = new Person(-1,"lihua");
}
}
测试结果如下:
这种方式既可以检查异常类型,也可以验证异常中的消息,而且用起来也比较简洁。
参考:https://blog.csdn.net/michaellufhl/article/details/5955098
更多推荐
所有评论(0)