unit-test-exception-handler

Installation
Summary

Unit testing patterns for Spring @ExceptionHandler and @ControllerAdvice global exception handlers.

  • Test exception-to-error-response transformations and HTTP status codes using MockMvc with setControllerAdvice() to register handlers
  • Verify error response structure includes required fields (timestamp, status, error, message) and test field-level validation errors from MethodArgumentNotValidException
  • Cover multiple exception types with appropriate status codes (404, 409, 401, 403, 500) and test logging or side effects triggered by handlers
  • Use mock test controllers that throw exceptions to trigger handler behavior without full integration test overhead
SKILL.md

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()
Related skills

More from giuseppe-trisciuoglio/developer-kit

Installs
875
GitHub Stars
246
First Seen
Feb 3, 2026