I have following POJO:
import java.util.Optional;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.immutables.value.Value;
@Value.Immutable
public interface ABC {
Optional<@NotBlank String> test();
Optional<@Size(max = 280) String> testSize();
}
I am using javax validation to validate objects of class ABC like following:
public static Set<TestConstraintViolation> validateInternalTest(final Object type, final Class<?>... groups) {
Set<TestConstraintViolation> violations = new HashSet<>();
for (Method method : type.getClass().getInterfaces()[0].getDeclaredMethods()) {
try {
VALIDATOR.validateReturnValue(
type,
method,
method.invoke(type),
groups).forEach(constraint -> {
TestConstraintViolation testConstraintViolation = new TestConstraintViolation(
method.getName(),
constraint.getMessageTemplate()
);
violations.add(testConstraintViolation);
});
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("", e);
}
}
return violations;
}
Now, when I try to validate with this validator function objects of ABC, I am seeing a weird issue:
@Test
public void test() {
ABC abc = ABCType.builder().build();
assertThat(validateInternalTest(abc))
.hasViolation("test", "{javax.validation.constraints.NotBlank.message}");
ABC abc2 = ABCType.builder().test("test").build();
assertThat(validateInternalTest(abc2))
.hasNoViolations();
}
With abc object, it returns violations if test is not passed even if it is optional while not passing testSize works fine.
According to me, with Optional, both of them should work. Isn't it?
Is it some issue with Immutables or javax validation? Please help.