Skip to content

Commit 719ea42

Browse files
committed
test(cucumber_fetch_and_save): add unit test for exception handler
1 parent 0c753cb commit 719ea42

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

src/test/java/com/xpeho/spring_boot_java_random_user/presentation/exceptions/GlobalExceptionHandlerTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,42 @@
33
import com.xpeho.spring_boot_java_random_user.domain.exceptions.InvalidPaginationException;
44
import com.xpeho.spring_boot_java_random_user.domain.exceptions.UserNotFoundException;
55
import com.xpeho.spring_boot_java_random_user.domain.enums.UserSource;
6+
import jakarta.validation.ConstraintViolation;
7+
import jakarta.validation.ConstraintViolationException;
68
import org.junit.jupiter.api.DisplayName;
79
import org.junit.jupiter.api.Test;
810
import org.springframework.http.HttpStatus;
911
import org.springframework.http.ResponseEntity;
1012
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
1113

14+
import java.util.Set;
15+
1216
import static org.junit.jupiter.api.Assertions.*;
17+
import static org.mockito.Mockito.mock;
18+
import static org.mockito.Mockito.when;
1319

1420
class GlobalExceptionHandlerTest {
1521

1622
private final GlobalExceptionHandler handler = new GlobalExceptionHandler();
1723

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+
1842
@Test
1943
@DisplayName("Should return 400 BAD_REQUEST when InvalidPaginationException is thrown")
2044
void shouldReturnBadRequestWhenInvalidPaginationException() {

0 commit comments

Comments
 (0)