手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网络编程>其它>列表

JUnit中如何测试异常

来源:互联网 作者:西部数码 时间:2008-04-09
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

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



-----------------------------------------
注:在这里Locale 参数并没有用到。
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) {}

}

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!