skip to content

Result Handlers & Debugging

Result handlers print or log the full exchange, which is how you debug a failing MockMvc test, and reusable expectations cut boilerplate. A practical detail that shows you have actually debugged these tests.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

In a MockMvc test, what does `.andDo(MockMvcResultHandlers.print())` do, and when would you use it?

level: juniorimportance: must knowfreq 62%

answer

  1. andDo runs a ResultHandler on MvcResult
  2. print() dumps request+response to System.out
  3. diagnostic only, never asserts
  4. print(OutputStream)/print(Writer) overloads
  5. shows status, headers, body, handler, ModelAndView

basics

~10 s

It prints the full request and response (URL, headers, status, body, handler) to System.out after the request runs. You add it to debug a failing test and see what the endpoint actually returned.

solid answer

~30 s

`.andDo(...)` runs a `ResultHandler` against the `MvcResult` after the request executes. `MockMvcResultHandlers.print()` is the built-in handler that dumps a formatted report to `System.out`: the `MockHttpServletRequest` (method, URI, params, headers), the selected handler/controller method, any resolved exception, the `ModelAndView`, flash attributes, and the `MockHttpServletResponse` (status, headers, body, forwarded/redirected URL). It changes nothing about the test outcome — it is purely diagnostic. You reach for it when an assertion fails and you cannot tell why: seeing the real status code and body usually reveals a wrong content type, a 401/403, or an error payload. Overloads let you redirect output: `print(OutputStream)` or `print(Writer)`.

code

java · 10 lines
java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@Test
void returnsUser() throws Exception {
    mockMvc.perform(get("/api/users/42"))
           .andDo(print())               // dumps full request/response to System.out
           .andExpect(status().isOk());  // the actual assertion
}

go deeper

for a junior

Know that andDo(print()) shows the request/response for debugging and does not assert anything.

for a middle

Explain the MvcResult contents it dumps and the print(OutputStream/Writer) overloads.

for a senior

Discuss noise/CI concerns and when to prefer log() or targeted matchers over blanket print().

for a principal

Weigh always-on printing vs. selective debugging across a large suite; standardize a policy (e.g., alwaysDo(log) not print).

**MockMvc result handlers** are a hook that runs *after* a simulated request completes, letting you inspect (not assert on) the outcome. The entry point is `ResultActions.andDo(ResultHandler)`. `ResultHandler` is a functional interface with a single method `void handle(MvcResult mvcResult)`, where `MvcResult` exposes the whole interaction: `getRequest()` (a `MockHttpServletRequest`), `getResponse()` (a `MockHttpServletResponse`), `getHandler()` (the controller method that matched), `getResolvedException()`, `getModelAndView()`, and `getFlashMap()`. `MockMvcResultHandlers` is a factory of ready-made handlers. `print()` returns a handler that writes a human-readable, multi-section report to `System.out`. A typical dump includes: - **MockHttpServletRequest**: HTTP method, request URI, parameters, headers, body. - **Handler**: the matched controller `@RequestMapping` method (or `null` for static/error paths). - **Async / Resolved Exception**: any exception a `HandlerExceptionResolver` handled. - **ModelAndView**: view name and model attributes (for MVC/view tests). - **FlashMap**: redirect flash attributes. - **MockHttpServletResponse**: status code, headers, content type, body, forwarded URL, redirected URL, cookies. Because it only reads `MvcResult`, `print()` never alters pass/fail — it is a debugging aid, not an assertion. Contrast with `MockMvcResultMatchers` (`.andExpect(...)`), which *do* assert. **Overloads and redirection**: `print()` writes to `System.out`; `print(OutputStream out)` and `print(Writer writer)` let you capture the report into a buffer or file. This matters when `System.out` is swallowed (some CI log configs) or when you want the dump attached to a test report. **Gotchas**: - The report reflects state *at the time the handler runs*. If you register it before other handlers/matchers, ordering can matter for async cases. - For binary or very large response bodies, the printed body can be huge or unreadable — prefer targeted matchers there. - `System.out` output can be lost or interleaved under parallel test execution; `log()` (see the related question) or `print(Writer)` is more robust in CI. **When to use**: temporarily, while diagnosing a failing endpoint test; remove or convert to `log()` once fixed so tests stay quiet.

  • Does `print()` affect whether the test passes or fails?
    No. It only reads the `MvcResult` and writes a report; it performs no assertions. Pass/fail is decided solely by `.andExpect(...)` matchers.
  • How would you send the printed report somewhere other than System.out?
    Use the overloads `print(OutputStream)` or `print(Writer)` — e.g. `print(new StringWriter())` to capture the dump into a buffer, or a file stream to persist it.

saying these in an interview costs you the question

  • Thinking print() asserts the response (it is purely diagnostic)
  • Believing print() is required for the test to run
  • Confusing MockMvcResultHandlers.print() with MockMvcResultMatchers

context

open as a page

What does `apply(springSecurity())` do when building a MockMvc, and why is it needed before using postprocessors like `user(...)` or `csrf()`?

level: seniorimportance: must knowfreq 55%

basics

~10 s

springSecurity() is a MockMvcConfigurer that wires Spring Security's filter chain into MockMvc. Without it, security filters don't run, so authentication/authorization and the csrf()/user() request postprocessors have no effect.

open as a page

What is the difference between `MockMvcResultHandlers.print()` and `MockMvcResultHandlers.log()`?

level: middleimportance: should knowfreq 40%

basics

~10 s

Both dump the same request/response report. print() writes to System.out (always visible), while log() writes it through SLF4J/commons-logging at DEBUG level, so it only appears if that logger's DEBUG level is enabled.

open as a page

How do `alwaysDo(...)` and `alwaysExpect(...)` on a MockMvc builder work, and when would you use them?

level: seniorimportance: should knowfreq 34%

basics

~10 s

They register a ResultHandler (alwaysDo) or ResultMatcher (alwaysExpect) once on the builder, and it runs automatically on every request performed by that MockMvc — so you don't repeat .andDo(...)/.andExpect(...) in each test.

open as a page

How would you standardize MockMvc debugging and security across a large test suite using result handlers, `alwaysDo`, and `apply(springSecurity())` — and what are the trade-offs?

level: principalimportance: nice to knowfreq 20%

basics

~10 s

Build a shared MockMvc via a base class or MockMvcBuilderCustomizer: apply(springSecurity()) for security plus alwaysDo(log()) for uniform, DEBUG-gated diagnostics. Keep global alwaysExpect minimal and add custom ResultHandlers only for cross-cutting captures.

open as a page