如何断言异常和错误消息
文章目录
通常,在向验证器和其他引发异常的方法写入junit时,我们将使用
-
测试方法上的
@Test(expected)
注释只验证异常类或 -
在测试方法和catch块中使用
try catch
,在异常的getMessage()
上写assert
语句来验证错误信息。
实时,我们将不得不断言异常类型及其错误消息。如果我们对每一个业务条件都使用 try catch,那么测试代码看起来很不整洁并且难以阅读。
Junit 库提供了一个名为ExpectedException
的特殊组件,用于在@Rule
注释的帮助下验证异常类型及其消息。让我们看看下面的例子
异常类
package com.wsq;
public class UserException extends Exception {
public UserException(String message) {
super(message);
}
}
验证器类
package com.wsq;
public class UserValidator {
public void validateUserID(String userID) throws UserException {
if(userID == null) {
throw new UserException("UserId is Null");
}
if(! userID.startsWith("USER")) {
throw new UserException("UserId is Invalid");
}
}
}
验证Test测试类
package com.wsq;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class UserValidatorTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void whenUserIDIsNull() throws Exception {
expectedEx.expect(UserException.class);
expectedEx.expectMessage("UserId is Null");
UserValidator validator = new UserValidator();
validator.validateUserID(null);
}
@Test
public void whenUserIDIsInvalid() throws Exception {
expectedEx.expect(UserException.class);
expectedEx.expectMessage("UserId is Invalid");
UserValidator validator = new UserValidator();
validator.validateUserID("12345");
}
}
最后喜欢的小伙伴,记得关注收藏哦!😏🍭😘