如何断言异常和错误消息

如何断言异常和错误消息


通常,在向验证器和其他引发异常的方法写入junit时,我们将使用

  1. 测试方法上的@Test(expected) 注释只验证异常类或

  2. 在测试方法和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");
        
    }
}

最后喜欢的小伙伴,记得关注收藏哦!😏🍭😘

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值