JUnit中如何测试异常

2005-11-04

   很多时候,我们要写一些单元测试来测试我们程序是否能正确触发异常。比如下面的例子中,我们就写了一个test case来测试一个Email验证类EmailAddrValidator,这个类有一个doValidate(email)方法可以验证email是否合法,如果不合法则会抛出ValidationException异常。因此我们写了两个方法来进行单元测试,前一个方法testDoValidate用来测试正常值,后一个方法testDoValidateException用来测试对错误的email格式是否能正确触发异常。
import junit.framework.TestCase;

public class TestEmailAddrValidator extends TestCase {
    EmailAddrValidator validator = new EmailAddrValidator();

    public void testDoValidate() throws ValidationException {
        validator.doValidate("glchengang@163.com", null);
        validator.doValidate("glchen.gang@163.com", null);
        validator.doValidate("glchen_gang@163.com", null);
        validator.doValidate("glchen.gang@163_tom.com", null);
    }

    public void testDoValidateException() {
        testDoValidateException("@b.c");
        testDoValidateException("a@.c");
        testDoValidateException("a@b.");
        testDoValidateException("@.c");
        testDoValidateException("@...");
        testDoValidateException(" ");
        testDoValidateException(null);
    }

    private void testDoValidateException(String email) {
        try {
            validator.doValidate(email, null);
            fail("末抛出异常");
        } catch (ValidationException e) {
            assertTrue(true);
        }
    }
}

例程说明: 这个例子的关键是方法testDoValidateException(String email) 。

import java.util.Locale;
import com.hygensoft.common.configure.ConfigureObject;

public class EmailAddrValidator{

    protected static final String ERROR_CODE_INVALID_EMAIL_ADDR = "INVALID_EMAIL_ADDR";
    protected static final String ERROR_CODE_INVALID_INPUT = "INVALID_INPUT_OBJECT";

    public Object doValidate(Object input, Locale locale) throws ValidationException {
        if (!(input instanceof String)) {
            throw new ValidationException(ERROR_CODE_INVALID_INPUT, input);
        }
        String inputStr = (String) input;
        int idx = inputStr.indexOf('@');
        if (idx == -1 || idx == 0) {
            throw new ValidationException(ERROR_CODE_INVALID_INPUT, input);
        }
        int idx2 = inputStr.indexOf('.', idx);
        if (idx2 == -1 || idx2 == idx + 1) {
            throw new ValidationException(ERROR_CODE_INVALID_INPUT, input);
        }
        if (inputStr.endsWith(".")) {
            throw new ValidationException(ERROR_CODE_INVALID_INPUT, input);
        }
        return input;
    }

    /* (non-Javadoc)
     * @see com.hygensoft.common.configure.Configurable#initialize(com.hygensoft.common.configure.ConfigureObject)
     */
    public void initialize(ConfigureObject conf) {}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值