1

I have the following test that fails:

 @Test
 public void testValidation() {
    Validator validator = new LocalValidatorFactoryBean();
    Map<String, String> map = new HashMap<String, String>();
    MapBindingResult errors = new MapBindingResult(map, Foo.class.getName());

    Foo foo = new Foo();
    foo.setBar("ba");
    validator.validate(foo, errors);
    assertTrue(errors.hasFieldErrors());
 }

Foo is as follows:

import javax.validation.constraints.Size;
public class Foo {
    @Size(min=9, max=9)
    private String bar;

    // ... public setter and getter for bar
}

I have referenced Manually call Spring Annotation Validation and Using Spring Validator outside of the context of Spring MVC but I'm not sure why this test is failing.

Community
  • 1
  • 1
James
  • 2,876
  • 18
  • 72
  • 116
  • 1
    Call `afterPropertiesSet` on the `LocalValidatorFactoryBean` before doing validation, without it it isn't properly setup. – M. Deinum Jul 14 '16 at 06:49
  • That was the missing piece. If you post an answer with this solution, I'll mark it as the correct answer. I'm curious of how you determined this as the solution (e.g. examined the source code, found documentation, etc.) so that I can read more about this if you found it in documentation. Thanks for your help. – James Jul 14 '16 at 15:15

1 Answers1

2

You are trying to use a bean that is actually to be used inside a Spring ApplicationContext outside of it. To prepare it for use you also have to mimic the behavior of the ApplicationContext in regards to object initialization.

The LocalValidatorFactoryBean implements the InitializingBean interface. Which contains a single method which will be normally called by the ApplicationContext once the object is constructed and all dependencies have been injected (the same as a method annotated with @PostConstruct).

As you are using the bean outside of an ApplicationContext you will have to call the afterPropertiesSet method manually before the object is actually ready to be used.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224