对于Override Validate()方法,Jmockit测试失败并出现null ponter异常

时间:2015-07-30 04:47:42

标签: java validation jsf jmockit

@Override
    public void validate(FacesContext facesContext, UIComponent uiComponent,
            Object emailId) throws ValidatorException {
        int userId = 0;
        try {
            AddNewUserDAO addNewUserDAO = new AddNewUserDAO();
            userId = addNewUserDAO.getUserIdWithUserName(emailId.toString());
        } catch (Exception exception) {
            LOGGER.error(exception);
        }
        matcher = pattern.matcher(emailId.toString());
        if (!matcher.matches()) {
            FacesMessage msg = new FacesMessage(new MessageProvider().getValue("prometheus_emailvalidation"));
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }
        if (userId != 0) {
            FacesMessage msg = new FacesMessage(
                    new MessageProvider().getValue("prometheus_userexists"));
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }

    }

我正在尝试用Jmockit编写测试用例,但我得到空指针异常,在这个方法中我们使用数据库查询(userId = addNewUserDAO.getUserIdWithUserName(emailId.toString());) 这就是为什么无法模拟,如何在这样的验证方法中模拟数据库查询和对象实例化其他类

1 个答案:

答案 0 :(得分:0)

Jmockit测试失败,覆盖方法

的空ponter异常

在这样的测试用例中模拟faces上下文。退出emailId时,您的异常升级。所以在@Test中使用预期。

    @Test(expected = javax.faces.validator.ValidatorException.class)
public void testValidatorWithExistedMailId(@Mocked FacesContext faces) {
    EmailIdExistanceValidator emailExistanceValidator=new EmailIdExistanceValidator();
    UIComponent uiComponent=null;
    emailExistanceValidator.validate(faces, uiComponent, "exitedId@gmail.com");
    assertNotNull(FacesMessage.VALUES);
}

@Test()
public void testValidatorWithUnExistedMailId(@Mocked FacesContext faces,@Mocked FacesMessage msg) {
    EmailIdExistanceValidator emailExistanceValidator=new EmailIdExistanceValidator();
    UIComponent uiComponent=null;
    emailExistanceValidator.validate(faces, uiComponent, (Object)"unexitedId@gmail.com");
    assertNotNull(FacesMessage.VALUES);
}