I\'m using Spring Validator implementations to validate my object and I would like to know how do you write a unit test for a validator like this one:
public
It is a really straight forward test without any mock. (just the error-object creation is a bit tricky)
@Test
public void testValidationWithValidAddress() {
AdressValidator addressValidator = new AddressValidator();
CustomValidator validatorUnderTest = new CustomValidator(adressValidator);
Address validAddress = new Address();
validAddress.set... everything to make it valid
Errors errors = new BeanPropertyBindingResult(validAddress, "validAddress");
validatorUnderTest.validate(validAddress, errors);
assertFalse(errors.hasErrors());
}
@Test
public void testValidationWithEmptyFirstNameAddress() {
AdressValidator addressValidator = new AddressValidator();
CustomValidator validatorUnderTest = new CustomValidator(adressValidator);
Address validAddress = new Address();
invalidAddress.setFirstName("")
invalidAddress.set... everything to make it valid exept the first name
Errors errors = new BeanPropertyBindingResult(invalidAddress, "invalidAddress");
validatorUnderTest.validate(invalidAddress, errors);
assertTrue(errors.hasErrors());
assertNotNull(errors.getFieldError("firstName"));
}
BTW: if you really want to make it more complicate and make it complicate by a mock, then have a look at this Blog, they use a two mocks, one for the object to test (ok, this is useful if you can not create one), and a second for the Error object (I think this is more complicated the it must be.)