Search code examples
javavalidationjsfjmockit

Jmockit tests fail with null ponter exception for Override Validate() method


@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);
        }

    }

I am trying to write a test case with Jmockit but I am getting null pointer exception, in this method we are using database queries( userId = addNewUserDAO.getUserIdWithUserName(emailId.toString());) which is why unable to mockit, how to mock database queries and object instantiate of other classes in such validator methods


Solution

  • Jmockit tests fail with null ponter exception for Override method

    Just mock the faces context in test case like this. Your are rising exception when exited emailId. So use expected in @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, "[email protected]");
        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)"[email protected]");
        assertNotNull(FacesMessage.VALUES);
    }