MockMvc exercises Spring MVC request handling through servlet test objects, so a test can inspect conversion, validation, handlers and responses without opening a listening socket.
Spring MockMvc tests: HTTP behavior without claiming a real network test
This lesson uses the downloadable source kit: Java 21, Spring Boot 4.0.8 and its managed Spring Framework 7 dependencies. The version is pinned for repeatable builds.
Choose what the fixture includes
ReceiptBoundaryTest constructs the controller directly, installs ReceiptErrors and a validator, and checks JSON requests. This standalone setup covers those supplied components. It does not discover every application bean or automatically install the full security chain.
The security tests use a web application context and apply Spring Security integration when checking authenticated-user CSRF behavior. Omitting that integration would let a controller test pass while proving nothing about the real protected route.
Assert the observable contract
The positive amount test checks 201 and amountMinor in the JSON response. The missing identifier checks 404 and the ProblemDetail media type. Rejection tests use invalid inputs and check the resulting status, rather than mirroring private method names.
The kit also uses a real random-port HTTP server for public health, anonymous access and CORS. A mock request cannot establish actual socket binding or every container behavior. Pick the smallest boundary that supplies evidence for the claim.
Checked source
var validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
MockMvc mvc = MockMvcBuilders.standaloneSetup(new ReceiptController(new ReceiptStore()))
.setControllerAdvice(new ReceiptErrors()).setValidator(validator).build();Test the boundary
Run mvn test in the source-kit directory. ReceiptBoundaryTest and HttpSecurityBoundaryTest checks the behavior described here. Java excerpts belong to the named source-kit classes; they are not independent source files unless the complete class is shown.
Costs and boundaries
Standalone MVC tests avoid server startup but still initialize request handling. More complete context tests cost more assembly time and catch different problems; neither should replace all direct Java tests.
Common Mistakes
- Do not call a standalone MVC test a full security test.
- Check response shape as well as status.
- Use a real server when socket and container behavior are part of the claim.
Read next
Testing boundaries, Spring Security filter chain: authentication, CSRF and request order, Java JUnit tests: boundary cases and observable contracts.
Continue with Spring delivery contracts
Continue with Spring MockMvc standalone tests: know which HTTP layers were assembled.
