【问题标题】:Jmockit tests fail with null ponter exception for Override Validate() methodJmockit 测试因 Override Validate() 方法的 null ponter 异常而失败
【发布时间】:2015-07-30 04:47:41
【问题描述】:
@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());) 这就是为什么无法 mockit,如何在此类验证器方法中模拟数据库查询和其他类的对象实例化

【问题讨论】:

    标签: java validation jsf jmockit


    【解决方案1】:

    Jmockit 测试因 Override 方法的 null ponter 异常而失败

    像这样在测试用例中模拟面孔上下文。退出 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-07
      • 1970-01-01
      • 2014-04-09
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多