liveBook · Manning

@RestControllerAdvice

As explained in Testing Spring Boot Applications

@ControllerAdvice is a Spring annotation for sharing cross-controller behavior such as exception handling and data binding.

Controller advice centralizes behavior shared across controllers, especially exception handling. In a Spring MVC test, it lets a focused web-layer test exercise error responses without loading the application’s full business logic. section 5.3

Handling a duplicate-city error

A controller advice catches CityAlreadySelectedException and returns HTTP 409 with the body "City already selected". The corresponding @WebMvcTest selects CityController, mocks CityService, triggers the exception, and verifies the conflict response through MockMvcTester. section 5.3

The focused test context includes controller advice among its recognized web components. @WebMvcTest can restrict the context to selected controllers while retaining the minimal infrastructure and testing utilities needed to exercise their web behavior. section 5.7.2 section 5.3

Practical testing choices include:

  • Use @SpringBootTest when the application is small or full-context coverage remains readable and performant. section 5.3
  • Use @WebMvcTest for isolated web edge cases when a larger application makes full-context tests unwieldy. section 5.3
  • Customize included or excluded types only when the default slice selection does not meet the testing need. section 5.7.2

How Testing Spring Boot Applications covers it

How deep it goes
Demonstrates exception-to-response handling and slice inclusion, but does not detail advice implementation beyond the focused example.
Examples
Uses a duplicate-city exception, an HTTP 409 response, a selected city controller, and a mocked service interaction.
What it assumes
Assumes Spring MVC controllers and exceptions, while demonstrating the testing setup needed to isolate them from business logic.
What you can do after
Diagnose web error behavior by triggering controller exceptions and asserting the resulting HTTP status and response body.
How it connects
Connects controller advice with @ExceptionHandler, @WebMvcTest, @Controller, ResponseEntity, and MockMvcTester.

Also explained in

Compare how 2 books explain @RestControllerAdvice →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.