Skip to content

Commit 81c6137

Browse files
committed
test: write tests for global exception handler #2
1 parent 92170f3 commit 81c6137

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package ch.puzzle.pcts;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import ch.puzzle.pcts.dto.error.GenericErrorDto;
6+
import ch.puzzle.pcts.exception.PCTSException;
7+
import ch.puzzle.pcts.model.error.ErrorKey;
8+
import org.junit.jupiter.api.DisplayName;
9+
import org.junit.jupiter.api.Test;
10+
import org.springframework.http.HttpStatus;
11+
import org.springframework.http.ResponseEntity;
12+
import org.springframework.validation.BindException;
13+
14+
class GlobalExceptionHandlerIT {
15+
16+
private final GlobalExceptionHandler handler = new GlobalExceptionHandler();
17+
18+
@DisplayName("Should return internal server error")
19+
@Test
20+
void shouldReturnInternalServerErrorResponse() {
21+
Exception ex = new Exception("Test exception");
22+
23+
ResponseEntity<GenericErrorDto> response = handler.handleGenericException(ex);
24+
25+
assertThat(response.getStatusCode().value()).isEqualTo(500);
26+
27+
GenericErrorDto body = response.getBody();
28+
assertThat(body).isNotNull();
29+
assertThat(body.key()).isEqualTo(ErrorKey.INTERNAL);
30+
assertThat(body.reasons()).containsExactly("Something has gone wrong on the server, please check the logs");
31+
}
32+
33+
@DisplayName("Should handle bind exception")
34+
@Test
35+
void shouldHandleBindException() {
36+
BindException ex = new BindException("Test exception", "Test bind exception");
37+
38+
ResponseEntity<GenericErrorDto> response = handler.handle(ex);
39+
40+
assertThat(response.getStatusCode().value()).isEqualTo(400);
41+
42+
GenericErrorDto body = response.getBody();
43+
assertThat(body).isNotNull();
44+
assertThat(body.key()).isEqualTo(ErrorKey.VALIDATION);
45+
assertThat(body.reasons()).containsExactly();
46+
}
47+
48+
@DisplayName("Should return pcts exception")
49+
@Test
50+
void shouldReturnPctsException() {
51+
PCTSException ex = new PCTSException(HttpStatus.BAD_REQUEST, "Test Pcts exception", ErrorKey.ID_IS_NOT_NULL);
52+
53+
ResponseEntity<GenericErrorDto> response = handler.handlePCTSException(ex);
54+
55+
assertThat(response.getStatusCode().value()).isEqualTo(400);
56+
57+
GenericErrorDto body = response.getBody();
58+
assertThat(body).isNotNull();
59+
assertThat(body.key()).isEqualTo(ErrorKey.ID_IS_NOT_NULL);
60+
assertThat(body.reasons()).containsExactly("Test Pcts exception");
61+
}
62+
}

0 commit comments

Comments
 (0)