|
3 | 3 | import com.xpeho.spring_boot_java_random_user.domain.exceptions.InvalidPaginationException; |
4 | 4 | import com.xpeho.spring_boot_java_random_user.domain.exceptions.UserNotFoundException; |
5 | 5 | import com.xpeho.spring_boot_java_random_user.domain.enums.UserSource; |
| 6 | +import jakarta.validation.ConstraintViolation; |
| 7 | +import jakarta.validation.ConstraintViolationException; |
6 | 8 | import org.junit.jupiter.api.DisplayName; |
7 | 9 | import org.junit.jupiter.api.Test; |
8 | 10 | import org.springframework.http.HttpStatus; |
9 | 11 | import org.springframework.http.ResponseEntity; |
10 | 12 | import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; |
11 | 13 |
|
| 14 | +import java.util.Set; |
| 15 | + |
12 | 16 | import static org.junit.jupiter.api.Assertions.*; |
| 17 | +import static org.mockito.Mockito.mock; |
| 18 | +import static org.mockito.Mockito.when; |
13 | 19 |
|
14 | 20 | class GlobalExceptionHandlerTest { |
15 | 21 |
|
16 | 22 | private final GlobalExceptionHandler handler = new GlobalExceptionHandler(); |
17 | 23 |
|
| 24 | + @Test |
| 25 | + @DisplayName("Should return 400 BAD_REQUEST when ConstraintViolationException is thrown") |
| 26 | + void shouldReturnBadRequestWhenConstraintViolationException() { |
| 27 | + ConstraintViolation<?> violation = mock(ConstraintViolation.class); |
| 28 | + when(violation.getPropertyPath()).thenReturn(mock(jakarta.validation.Path.class)); |
| 29 | + when(violation.getPropertyPath().toString()).thenReturn("size"); |
| 30 | + when(violation.getMessage()).thenReturn("must be less than or equal to 30"); |
| 31 | + |
| 32 | + ConstraintViolationException ex = new ConstraintViolationException(Set.of(violation)); |
| 33 | + ResponseEntity<ErrorResponse> response = handler.handleConstraintViolationException(ex); |
| 34 | + |
| 35 | + assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); |
| 36 | + assertNotNull(response.getBody()); |
| 37 | + assertEquals("INVALID_PARAMETER", response.getBody().error()); |
| 38 | + assertEquals(400, response.getBody().status()); |
| 39 | + assertTrue(response.getBody().message().contains("must be less than or equal to 30")); |
| 40 | + } |
| 41 | + |
18 | 42 | @Test |
19 | 43 | @DisplayName("Should return 400 BAD_REQUEST when InvalidPaginationException is thrown") |
20 | 44 | void shouldReturnBadRequestWhenInvalidPaginationException() { |
|
0 commit comments