public class EmailValidator implements Validator {
public void validate(FacesContext context, UIComponent arg1, Object value)
throws ValidatorException {
String email = (String) value;
if (!email.contains("@")) {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(" Email is not valid.");
message.setDetail(" Email is not valid.");
context.addMessage("userForm:Email", message);
throw new ValidatorException(message);
}
}
}
问问题
2611 次
1 回答
5
你想在这里测试什么?如果if (!email.contains("@"))
在工作?如果您想从用户的角度对此进行测试,您需要使用Selenium 之类的东西进行集成或 GUI 测试。
如果您想对电子邮件验证进行单元测试,我会在课堂上这样做:
public class EmailValidator implements Validator {
public void validate(FacesContext context, UIComponent arg1, Object value)
throws ValidatorException {
String email = (String) value;
if (!isValidEmail(email)) {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(" Email is not valid.");
message.setDetail(" Email is not valid.");
context.addMessage("userForm:Email", message);
throw new ValidatorException(message);
}
}
boolean isValidEmail(String emailAddress){
// do your tests here...
}
}
然后编写一个这样的测试类:
public class EmailValidatorTest {
@Test
public testIsValidEmail(){
EmailValidator validator = new EmailValidator();
Assert.assertTrue(validator.isValidEmail("foo@bar.com");
Assert.assertFalse(validator.isValidEmail("aaa");
// more assertions here...
}
}
编辑
好吧,您可以通过提供所谓的Mock objects来为该方法编写测试。然后,您只希望在提供的电子邮件地址无效时发生异常:
public class EmailValidatorTest{
@Test
public void testValidateWithValidAddresses(){
FacesContextMock facesContextMock = new FacesContextMock();
EmailValidator validator = new EmailValidator();
validator.validate(facesContextMock, null, "foo@bar.com");
}
@Test(expected=ValidatorException.class)
public void testValidateWithInvalidAddresses(){
FacesContextMock facesContextMock = new FacesContextMock();
EmailValidator validator = new EmailValidator();
validator.validate(facesContextMock, null, "foo");
}
}
FacesContextMock 只是一个模型,它实现了 FacesContext 方法而不做任何事情:
public class FacesContextMock extends FacesContext{
@Override
public Application getApplication(){
return null;
}
// all the abstract methods implemented here, just doing nothing
}
也就是说,我认为您不必为了接近 100% 的代码覆盖率而为所有内容编写测试用例。我认为应该测试什么以及需要多少代码覆盖率在https://sqa.stackexchange.com/上进行了详细讨论
于 2012-07-23T10:33:12.973 回答