Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, October 26, 2011

Creating a Spring Errors Object for Validation Unit Tests

If you're using Spring Validation, you write classes that implement the following method

public void validate(Object arg0, Errors arg1);

"Errors" is an interface that is implemented by several other classes in the Spring Validation libraries: BeanPropertyBindingResult, DirectFieldBindingResult, MapBindingResult, and BindException.

I write unit tests using BeanPropertyBindingResult.  This is the class used in some of the Spring Validation unit tests like ValidationUtilsTests.

So, a JUnit4 unit test looks like

@Test
public void needsFirstName() {
  Person p = new Person();  // no firstName set
  Errors errors = new BeanPropertyBindingResult(p, "p");
  validator.validate(p, errors);  // 'validator' under test
  assertTrue(errors.hasErrors());
  assertNotNull( errors.getFieldError("firstname") );
}


4 comments: