我在下面得到了以下测试用例并有一个问题。为什么没有groups参数的嵌套属性验证总是失败?如何在没有组的情况下验证嵌套属性?
提前谢谢
亲切的问候
基督教
我的测试用例:
package validation;
import java.util.Set;
import javax.validation.*;
import javax.validation.constraints.*;
import junit.framework.Assert;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.*;
@Slf4j
public class NestedPropertiesTest {
private ValidatorFactory factory;
private Validator validator;
@Before
public void setUp() throws Exception {
log.info("\n\nTest start:");
this.factory = Validation.buildDefaultValidatorFactory();
this.validator = factory.getValidator();
}
@Test
public void testNestedBarNullValue() {
Foo foo = new Foo();
Bar bar = new Bar();
bar.setNotempty(null);
foo.setBar(bar);
log.info("With groups:");
Set<ConstraintViolation<Foo>> errors = validator.validateProperty(foo, "bar.notempty", Checks.class);
logErrors(errors);
Assert.assertFalse(errors.isEmpty());
log.info("Without groups:");
errors = validator.validateProperty(foo, "bar.notempty");
logErrors(errors);
Assert.assertFalse(errors.isEmpty());
}
@Test
public void testNestedBarMinSize() {
Foo foo = new Foo();
Bar bar = new Bar();
bar.setNotempty("1");
foo.setBar(bar);
log.info("With groups:");
Set<ConstraintViolation<Foo>> errors = validator.validateProperty(foo, "bar.notempty", Checks.class);
logErrors(errors);
Assert.assertFalse(errors.isEmpty());
log.info("Without groups:");
errors = validator.validateProperty(foo, "bar.notempty");
logErrors(errors);
Assert.assertFalse(errors.isEmpty());
}
@SuppressWarnings("rawtypes")
private void logErrors(Set errors) {
log.info("Nr. of validation errors: {}", errors.size());
for (Object error : errors) {
ConstraintViolation cv = (ConstraintViolation) error;
log.info("{}: {}", cv.getPropertyPath(), cv.getMessage());
}
}
@Data private class Foo {
@Valid private Bar bar;
}
@Data private class Bar {
@NotNull(groups=Checks.class)
@Size(min = 2, groups=Checks.class)
private String notempty;
}
private interface Checks {}
}
我的pom(以防万一):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>noorg</groupId>
<artifactId>validation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>0.11.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
</project>