带有spring组件的javax.validator [英] javax.validator with spring component
问题描述
我在Spring中使用javax.validation.在测试中(常规),我明确创建了验证器.
import javax.validation.Validation
import javax.validation.Validator
import javax.validation.ValidatorFactory
ValidatorFactory factory = Validation.buildDefaultValidatorFactory()
Validator validator = factory.getValidator()
when:
Set<ConstraintViolation<User>> constraints = validator.validate(entity)
我在Java中的验证器
public class EntityDynamicValidator implements ConstraintValidator<SomeConstraint, Entity> {
private GroupService groupService;
// This constructor is required, see the link bellow.
public UserDynamicEnumValidator() {
}
public UserDynamicEnumValidator(final GroupService groupService) {
this.groupService = groupService;
}
@Override
public boolean isValid(final Entity entity, final ConstraintValidatorContext context) {
Something something = groupService.findByValue(entity.getValue());
// Validate all this stuff
}
}
我需要将Spring 服务传递给验证器.
我有一个默认的构造函数,因为有一个问题 Validator的春季单元测试问题
我也尝试解决此问题,但是测试对我来说是完全低级的单元测试,我希望避免过多的上下文.我什至无法使用您的方法.我这边的解决方案是将一个自定义ConstraintValidatorBean添加到嘲笑mvcvc中.该自定义实现可以获取验证器类Class对象的列表,因此,如果工厂尝试创建验证器,我将返回它的Mockito.mock版本,而不是真正的验证器版本. >
I use javax.validation with Spring. In my test (groovy) I explicitly create validator.
import javax.validation.Validation
import javax.validation.Validator
import javax.validation.ValidatorFactory
ValidatorFactory factory = Validation.buildDefaultValidatorFactory()
Validator validator = factory.getValidator()
when:
Set<ConstraintViolation<User>> constraints = validator.validate(entity)
My validator in java
public class EntityDynamicValidator implements ConstraintValidator<SomeConstraint, Entity> {
private GroupService groupService;
// This constructor is required, see the link bellow.
public UserDynamicEnumValidator() {
}
public UserDynamicEnumValidator(final GroupService groupService) {
this.groupService = groupService;
}
@Override
public boolean isValid(final Entity entity, final ConstraintValidatorContext context) {
Something something = groupService.findByValue(entity.getValue());
// Validate all this stuff
}
}
I need to pass a Spring service to the validator.
I have a default constructor because there is an issue Spring unit test issue with Validator
I also tried to solve this, however the tests are fully low level unit tests on my side and I wanted to avoid too much of a context. I couldn't even use your approach. The solution my side was to add a custom ConstraintValidatorBean into the mockmvc. That custom implementation could get a list of validator class Class objects and so if the factory tried to create a validator, I returned a Mockito.mock version of it instead of the real one and I could also look that up for expectation settings.
这篇关于带有spring组件的javax.validator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!