liveBook · Manning

MockMvc

As explained in Spring Security in Action, Second Edition

MockMvc is a Spring testing utility that performs simulated HTTP requests against MVC application components without requiring a running server.

MockMvc performs simulated HTTP requests against Spring MVC components, allowing endpoint behavior and security configuration to be tested without a running server. section 18.1

A typical security test workflow is:

  • Annotate the test with @SpringBootTest and @AutoConfigureMockMvc, then autowire MockMvc. section 18.1
  • Call an endpoint with mvc.perform(get("/hello")) and assert the response status or content. section 18.1
  • Test unauthenticated and authenticated paths separately by omitting a user or adding one with @WithMockUser or user("mary"). section 18.1
Listing 18.2 Adding MockMvc for implementing test scenarios
@SpringBootTest
@AutoConfigureMockMvc        #1
public class MainTests {

  @Autowired
  private MockMvc mvc;       #2
}

Shows the minimal @AutoConfigureMockMvc setup and injected MockMvc field used to implement endpoint scenarios. section 18.1

How Spring Security in Action, Second Edition covers it

How deep it goes
Demonstrates setup, requests, response assertions, mock users, and SecurityContext behavior, while deferring reactive testing to WebTestClient.
Examples
Uses /hello requests expecting 401 Unauthorized without authentication and 200 OK with a mock user.
What it assumes
Assumes a Spring Boot test context and basic endpoint testing, while demonstrating mock authentication from configuration.
What you can do after
Apply it via Spring test annotations and MockMvc request builders to verify secured endpoint responses.
How it connects
Connects Spring Security endpoint authorization with SecurityContext, mock users, RequestPostProcessor, and method security.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.