Madu
Madu

Reputation: 5049

Working of javax.validation @NotBlank and lombok @NonNull

I have a simple User class and its properties are annotated with both @NotBland and lombok @NonNull.

@AllArgsConstructor
@Data
@Builder
public class User {

    @NonNull
    private String name;

    @NonNull
    private String id;

    @NotBlank
    private String address;
}

What i am expecting from this is when i try to set blank in address field it informs me at compile time or at least crash at runtime. Lombok @NonNull is working in that way and is raising NPEs at runtime.

I wrote the following test to check this

@Test
public void user_null_test(){

    User user = User.builder()
            .id("")
            .name("")
            .address("")
            .build();



    assertThat(user).isNotNull();

But the user is a valid user object with address being empty. Obviously i can use the following code to check for validation in my test

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertThat(violations).isEmpty(); 

but i can't do that or want to write this type of code in my actual code base. So my question is what is the use of @NotBlank if it does not raise any error at compile or run time if we are setting a property to as empty string when it is not supposed to be so according to the set annotation.

Upvotes: 1

Views: 2773

Answers (0)

Related Questions