1+ package com .baeldung .javaxval .notnull ;
2+
3+ import org .junit .jupiter .api .Test ;
4+ import org .springframework .beans .factory .annotation .Autowired ;
5+ import org .springframework .boot .autoconfigure .SpringBootApplication ;
6+ import org .springframework .boot .test .context .SpringBootTest ;
7+
8+ import javax .validation .ConstraintViolation ;
9+ import javax .validation .ConstraintViolationException ;
10+ import javax .validation .constraints .NotNull ;
11+ import java .util .Set ;
12+
13+ import static org .hamcrest .MatcherAssert .assertThat ;
14+ import static org .hamcrest .Matchers .is ;
15+ import static org .junit .jupiter .api .Assertions .assertThrows ;
16+
17+ @ SpringBootTest
18+ class ValidatingComponentIntegrationTest {
19+
20+ @ Autowired ValidatingComponent component ;
21+
22+ @ Test
23+ void givenValue_whenValidate_thenSuccess () {
24+ assertThat (component .validateNotNull ("Not null!" ), is (9 ));
25+ }
26+
27+ @ Test
28+ void givenNull_whenValidate_thenConstraintViolationException () {
29+ ConstraintViolationException constraintViolationException = assertThrows (ConstraintViolationException .class , () -> component .validateNotNull (null ));
30+ Set <ConstraintViolation <?>> constraintViolations = constraintViolationException .getConstraintViolations ();
31+ assertThat (constraintViolations .iterator ().next ().getConstraintDescriptor ().getAnnotation ().annotationType (), is (NotNull .class ));
32+ }
33+
34+ @ Test
35+ void givenNull_whenOnlyCalledMethodHasAnnotation_thenNoValidation () {
36+ assertThrows (NullPointerException .class , () -> component .callAnnotatedMethod (null ));
37+ }
38+
39+ @ SpringBootApplication
40+ static class TestApplication {
41+ }
42+
43+ }
0 commit comments