Micronaut multilevel bean validation

Pulkit Gupta :

I am working on Microanut version 1.2.0 and was trying to find a way to avoid redundant checks for possible data inconsistencies in the beans formed as a response to an external API. My idea is to validate the bean and that validation step should also validate the instance variables of the bean for possible violations.

For example, I have a student class which has an address field.

Student.java

@Data
@Builder
@Introspected
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    @NotNull
    String id;
    String name;
    Address address;
}

Address.java

@Data
@Builder
@Introspected
@NoArgsConstructor
@AllArgsConstructor
public class Address {
    @NotNull
    String houseNumber;
    String city;
}

Now when I am doing a bean validation on an instance of type Student, I want to cover the validation of instance variable address. Hence, in this case, a single validation should give errors for both a null Student.id and for a null Address.houseNumber. However, in my case, I am getting just one error and that is for a Null id in Student instance.

StudentTest.java

@Test
public void checkIfValidationsAreWorking() {
    System.out.println("Tests Started");
    // HouseNumber will be Null
    Address address = Address.builder()
            .city("Delhi")
            .build();
    // id will be Null
    Student student = Student.builder()
            .name("Pulkit")
            .address(address)
            .build();

    Set<ConstraintViolation<Student>> violations = validator.validate(student);

    violations.stream()
        .map(s -> s.getPropertyPath() + " " + s.getInvalidValue())
        .forEach(System.out::println);

    assertEquals(2, violations.size());

}

CONSOLE

Tests Started

id null

TEST RESULT: Test Failed, expected: <2> but was: <1>

Is there a way by which we can do complete bean validation including all the custom typed instance variables rather than doing it once on the main bean and then on all the instance variables of that beans which are of custom type?

Thanks.

mentallurg :

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148250&siteId=1