
Unit Test Exception Handler
Write MockMvc standalone tests for Spring @ControllerAdvice handlers, including mocked dependencies and SecurityContext-aware authorization cases.
Overview
Unit-test-exception-handler is an agent skill for the Ship phase that teaches Spring MockMvc patterns to test @ControllerAdvice exception handlers with mocks and security context.
Install
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-exception-handlerWhat is this skill?
- Standalone MockMvc setup with setControllerAdvice for GlobalExceptionHandler
- Constructor-injected dependencies mocked (e.g. MessageService) with verify on getMessage
- jsonPath assertions on ErrorResponse message fields for localized errors
- Patterns for handlers that read SecurityContextHolder / authorization failures
- Copy-paste Java examples for BusinessException BAD_REQUEST flows
Adoption & trust: 1.2k installs on skills.sh; 271 GitHub stars; 3/3 security scanners passed (skills.sh audits).
What problem does it solve?
Your GlobalExceptionHandler returns the right JSON in production but you lack fast standalone tests for dependencies, localization, and security-aware branches.
Who is it for?
Indie backend devs on Spring who already have @ControllerAdvice handlers and want isolated tests without @SpringBootTest weight.
Skip if: Non-Spring stacks, pure integration suites that only use @WebMvcTest end-to-end, or teams with no Java backend.
When should I use this skill?
When implementing or extending tests for Spring @ControllerAdvice exception handlers using MockMvc and mocks.
What do I get? / Deliverables
You get MockMvc test classes that assert status codes and error payloads and verify collaborator calls for each exception mapping.
- Handler test classes with status and jsonPath expectations
- Verified mock interactions for injected handler dependencies
Recommended Skills
Journey fit
Ship is where API error contracts and regression tests must be proven before release; exception handlers are critical path for client-facing stability. Testing subphase matches unit/integration-style handler verification with MockMvc, mocks, and status/jsonPath assertions.
How it compares
Template snippets for handler-focused unit tests, not a full mutation-testing or contract-test framework.
Common Questions / FAQ
Who is unit-test-exception-handler for?
Solo builders and small teams shipping Spring REST APIs who maintain centralized exception handlers and need reliable MockMvc coverage.
When should I use unit-test-exception-handler?
During Ship testing before release when adding or changing @ExceptionHandler methods, MessageService localization, or security-sensitive error responses.
Is unit-test-exception-handler safe to install?
It provides test code patterns only; review the Security Audits panel on this page and run tests in your own CI environment.
SKILL.md
READMESKILL.md - Unit Test Exception Handler
# Exception Handler Test Examples ## Handler with Dependencies (using mocks) When your `@ControllerAdvice` has dependencies injected via constructor, mock them in your test: ```java @ControllerAdvice public class GlobalExceptionHandler { private final MessageService messageService; public GlobalExceptionHandler(MessageService messageService) { this.messageService = messageService; } @ExceptionHandler(BusinessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleBusiness(BusinessException ex) { return new ErrorResponse(400, "Business Error", messageService.getMessage(ex.getErrorCode())); } } class HandlerWithDepsTest { private MockMvc mockMvc; private MessageService messageService = mock(MessageService.class); @BeforeEach void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .setControllerAdvice(new GlobalExceptionHandler(messageService)) .build(); } @Test void shouldReturnLocalizedMessage() throws Exception { when(messageService.getMessage("USER_NOT_FOUND")).thenReturn("Utente non trovato"); mockMvc.perform(get("/api/users/999")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.message").value("Utente non trovato")); verify(messageService).getMessage("USER_NOT_FOUND"); } } ``` ## Testing with Spring Security Context When your exception handler evaluates `SecurityContextHolder`: ```java @ExceptionHandler(AuthorizationException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public ErrorResponse handleAuth(AuthorizationException ex) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return new ErrorResponse(403, "Forbidden", "Access denied for: " + auth.getName()); } @Test void shouldReturn403WhenNotAuthorized() throws Exception { SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken("user", null, List.of()) ); mockMvc.perform(get("/api/admin")) .andExpect(status().isForbidden()) .andExpect(jsonPath("$.message").value("Access denied for: user")); } ``` ## Testing with MessageSource (Localization) ```java @ControllerAdvice public class I18nExceptionHandler { private final MessageSource messageSource; public I18nExceptionHandler(MessageSource messageSource) { this.messageSource = messageSource; } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFound(ResourceNotFoundException ex, Locale locale) { String message = messageSource.getMessage(ex.getMessage(), null, locale); return new ErrorResponse(404, "Not Found", message); } } @Test void shouldReturnLocalizedMessageItalian() throws Exception { // Inject MessageSource into MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .setControllerAdvice(new I18nExceptionHandler(messageSource)) .setLocaleResolver(() -> Locale.ITALIAN) .build(); mockMvc.perform(get("/api/users/999")) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.message").value("Utente non trovato")); } ``` --- 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 mo