I have springboot application which wires up validatorFactoryBean like this
private LocalValidatorFactoryBean validatorFactoryBean;
@Autowired
public void setValidatorFactoryBean(LocalValidatorFactoryBean validatorFactoryBean) {
this.validatorFactoryBean = validatorFactoryBean;
}
I have custom validators defined on class Car and I run the validations like this.
Set<ConstraintViolation<Car>> constraintViolations = validatorFactoryBean.validate(myCar);
All of this works fine. But when I try to test this thru unit tests, on the line
validatorFactoryBean.validate(myCar)
I get an error "No target Validator set".
This is how I am setting up validatorFactoryBean in the testng unit test
@InjectMocks
LocalValidatorFactoryBean validatorFactoryBean;
I pass this in to the class I am testing by calling setValidatorFactoryBean setter.
While debugging I realized this validatorFactoryBean is not aware of all the ConstraintValidator implementations in the main code.
How do I make validatorFactoryBean aware of all the ConstraintValidator implementations?
This is how the car constraint validator looks like
public class CarConstraintImpl implements ConstraintValidator<CarConstraint, req> {
@Inject
FuelDependency fuelDependency;
public CarConstraintImpl() {
}
@Override
public boolean isValid(Request req, ConstraintValidatorContext constraintContext) {
try {
fuelDependency.check(req);
} catch (Exception e) {
//some code
}
return true;
}
}
@InjectMocksis just a mockito stuff and never understand spring. It just like you create aLocalValidatorFactoryBeanmanually without any spring integration to it.To configure
LocalValidatorFactoryBeanproperly , you can do it by using@SpringBootTestwith the@ImportAutoConfigurationto auto-configure just the bean validation stuff.