标签:
在Junit 4.7之后,加入了一种更容易断言异常以及异常信息的方法。
//验证抛出异常类,以及错误信息
public class TestException {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void testValidationException() throws ValidationException {
//断言会抛出的异常,这句一定要在抛出异常之前,否则当异常抛出时,就会阻断运行之后的语句。
expectedEx.expect(ValidationException.class);
//断言得到的错误信息内容。注意:断言的信息可以是原错误信息的字串
expectedEx.expectMessage("is not passed");
throw new ValidationException("Password is not passed.");
}
}
//随意定义一个异常类
class ValidationException extends Exception{
ValidationException(String msg){
super(msg);
}
}
expectedEx.expectMessage方法在断言多种返回信息时非常有用。例如当验证密码的时候,有时候可能会断言一下两种异常:
throw new ValidationException(“密码必须包含字母和数字”);
throw new ValidationException(“密码不能大于16位”);
Junit 4.7 Rule:另一种断言异常的方法(ExpectedException)
标签:
原文地址:http://blog.csdn.net/ghostaaa/article/details/51354603