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);
}
}
}
答案 0 :(得分: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/
上详细讨论了应该测试的内容以及需要多少代码覆盖率