@Service
@Validated
public class ValidateService {
public void testValidation(String notValidated) {
testValidationNotNull(notValidated);
}
public void testValidationNotNull(@NotNull String validated) {
validated.isBlank();
}
}
I am expecting to get ConstraintViolationException when testValidation method is executed and notValidated string is null, but instead i get NPE since validated.isBlank() row is getting executed.
Is this the wanted bahavior from javax.validation.constraints.NotNull when the method is being called from another method in the same service layer?
Below are 2 test methods: 1 triggers NPE, 2 triggers ConstraintViolationException
@SpringBootTest
public class ValidateServiceTest {
@Autowired
private ValidateService sut;
// test that triggers NPE instead of ConstraintViolationException
@Test
public void testValidation() {
sut.testValidation(null);
}
// green test which triggers ConstraintViolationException
@Test
public void testValidationNotNull_shouldThrowConstraintsViolationException() {
final ConstraintViolationException violationException = assertThrows(ConstraintViolationException.class, () -> sut.testValidationNotNull(null));
assertEquals("testValidationNotNull.validated: must not be null", violationException.getMessage());
}
}
Here you are passing
nullas a method argument and after it you are trying to invokeisBlank()fromStringbut if you are going to check the java docs ofStringclass, before of all there is writing.it is the reason.
By the way I recommend you to check all answers of this question to have more details why. There also is present some good references to documentation.
The reason is simple:
Annotation has no effect because there’s no validator to enforce it. in another way :
@NotNull is just an annotation. Annotations do nothing on their own. They need an annotation processor at compile time, or something that processes it at runtime.
It is the reason why you got
NullPointerExceptionto fix it you also should invokeConstraintViolationExceptionas in second test-case