CustomerPassEqualsValidator implements Validator { @Override public void validate(Object target, Errors errors) { CustomerForm customer = (CustomerForm) target; String pass = customer.getCustomerPass(); String passConfirm = customer.getCustomerPassConfirm(); if (pass == null || passConfirm == null) { return; } if (!pass.equals(passConfirm)) { errors.rejectValue("customerPass", "NotEquals.customerPass", "Password and password confirm is not same."); } }  @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors);  }
@Test public void testValidate01() { CustomerPassEqualsValidator validator = new CustomerPassEqualsValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerPass("12345"); customer.setCustomerPassConfirm("12345"); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(false)); assertThat(result.getErrorCount(), is(0)); }
@Test public void testValidate02() { CustomerPassEqualsValidator validator = new CustomerPassEqualsValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerPass("12345"); customer.setCustomerPassConfirm("1234"); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(true)); FieldError error = result.getFieldError("customerPass"); if (error != null) { assertThat(error.getCode(), is("NotEquals.customerPass")); assertThat(error.getDefaultMessage(), is( "Password and password confirm is not same.")); } else { fail("error"); } }
@Test public void testValidate03() { CustomerPassEqualsValidator validator = new CustomerPassEqualsValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerPass("12345"); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(false)); assertThat(result.getErrorCount(), is(0)); }
@Test public void testValidate04() { CustomerPassEqualsValidator validator = new CustomerPassEqualsValidator(); CustomerForm customer = new CustomerForm(); customer.setCustomerPassConfirm("12345"); BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm"); validator.validate(customer, result); assertThat(result.hasErrors(), is(false)); assertThat(result.getErrorCount(), is(0)); }