Expert Spring MVC and Web Flow

(Dana P.) #1
}

return this.addressValidator;
}
}


pushNestedPathadds the path to the existing nested path if one is set; otherwise, the
nested path is set to the value being pushed. popNestedPathremoves the last nested path that
has been added to restore the nested path to the previous value.
Notice CustomerValidatormanages the nested path by means of pushing and popping
on the Errorsinstance. The AddressValidatorinstance is clueless that its caller is another
Validator; it is injected in CustomerValidator.


Testing Validators


Testing your validators—both declarative and programmatic validators—is important to verify
that they validate only validobjects. Declarative validators like those created with Valang should
be tested to verify the syntax and configuration work correctly. We only have to pass in an object
to validate, and an Errorsinstance so calling a Validatorfrom a test case is straightforward.
More challenging is verifying whether the correct error codes have been registered with
the Errorsinstance for specific validation errors. Spring 2.0 offers a convenience class to
check whether an Errorsinstance has only the error codes we expect. ErrorsVerifiercan be
found in the spring-mock.jar and offers methods to check the content of an Errorsinstance.
The test case in Listing 9-24 demonstrates the use of ErrorsVerifier. The
testEmptyPersonValidation()method validates a Personobject that has no values for
its properties and verifies whether the Errorsinstance contains the expected errors.


Listing 9-24.Using the ErrorsVerifier Class to Test the State of an Errors Instance


public class PersonValidatorTests extends TestCase {
public void testEmptyPersonValidation() {
Person person = new Person();
Validator validator = new PersonValidator();
BindException errors = new BindException(person, "target");
validator.validate(person, errors);


new ErrorsVerifier(errors) {
{
forProperty("firstName").hasErrorCode("person.firstName.required")
.forProperty("lastName").hasErrorCode("person.lastName.required")
.otherwise().noErrors();
}
}
}
}


The ErrorsVerifierclass uses a special notation. First of all we create an anonymous
class by calling new ErrorsVerifier(errors) {}. We pass in the Errorsinstance we want
to verify in the constructor and in the constructor body—which is again enclosed in curly


CHAPTER 9 ■VALIDATION 281
Free download pdf