SKILL.md--- name: unit-test-exception-handler description: Provides patterns for unit testing `@ExceptionHandler` and `@ControllerAdvice` in Spring Boot applications. Validates error response formatting, mocks exceptions, verifies HTTP status codes, tests field-level validation errors, and asserts custom error payloads. Use when writing Spring exception handler tests, REST API error tests, or mocking controller advice. allowed-tools: Read, Write, Bash, Glob, Grep --- # Unit Testing ExceptionHandler and ControllerAdvice ## Overview This skill provides patterns for writing unit tests for Spring Boot exception handlers. It covers testing `@ExceptionHandler` methods in `@ControllerAdvice` classes using MockMvc, including HTTP status assertions, JSON response validation, field-level validation error testing, and mocking handler dependencies. ## When to Use - Writing unit tests for `@ExceptionHandler` methods - Testing `@ControllerAdvice` global exception handling - Validating REST API error response formatting - Mocking exceptions in controller tests - Testing field-level validation error responses - Asserting custom error payloads and HTTP status codes ## Instructions 1. **Create a test controller** that throws specific exceptions to trigger each `@ExceptionHandler` 2. **Register ControllerAdvice** via `setControllerAdvice()` on `MockMvcBuilders.standaloneSetup()` 3. **Assert HTTP status codes** with `.andExpect(status().isXxx())` 4. **Verify error response fields** using `jsonPath("$.field")` matchers 5. **Test validation errors** by sending invalid payloads and checking `MethodArgumentNotValidException` produces field-level details 6. **Debug failures** with `.andDo(print())` — if handler not invoked, verify `setControllerAdvice()` is called and exception type matches ## Examples ### Exception Handler and Error DTO ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFound(ResourceNotFoundException ex) { return new ErrorResponse(404, "Not Found", ex.getMessage()); } @ExceptionHandler(ValidationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleValidation(ValidationException ex) { return new ErrorResponse(400, "Bad Request", ex.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorResponse handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(e -> errors.put(e.getField(), e.getDefaultMessage())); return new ValidationErrorResponse(400, "Validation Failed", errors); } } public record ErrorResponse(int status, String error, String message) {} public record ValidationErrorResponse(int status, String error, Map<String,