您的位置:首页 > 其它

junit 4中对指定异常的测试

2013-07-01 18:05 218 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: