Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 66 ยท Testing

Testing Controllers with MockMvc

Test Spring Boot controllers fast with @WebMvcTest, MockMvcTester and @MockitoBean: status codes, JSON assertions, validation errors and security.

A controller does a lot with very little code: it maps a URL and method to a Java method, converts JSON to objects and back, validates input, picks a status code and applies security rules. Almost none of that is visible in the Java code, which is exactly why it breaks silently. A typo in a path, a missing @RequestBody, a field name that does not match the JSON, or a validation message nobody tested: you want to find all of these without starting a server.

MockMvc is the tool. It drives Spring MVC's real request-handling machinery (mapping, argument resolution, message converters, validation, exception handlers, filters) without opening a network port. A web slice test (@WebMvcTest) loads only the web layer, so a test starts in about a second. This lesson shows how to write these tests, how to isolate the controller from its service, how to assert on JSON and how to include security. It follows the overview in Testing Spring Boot Applications.

Spring itself cannot run on this site, so the real test code is read-only. The TryIts build a miniature dispatcher and a MockMvc-like test helper in plain Java, so you can watch what such a test actually does.

What a web slice test does

Build request Method, URL, headers, body.
Dispatch Real mapping, converters and validation.
Mocked service No database, no network.
Assert Status, headers and JSON body.
1 / 2

A first web slice test

The slice annotation names the controller under test. Boot then creates only controllers (and @ControllerAdvice, filters and converters), not your @Service or @Repository beans. Whatever the controller needs, you provide with @MockitoBean:

Java
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    MockMvcTester mvc;

    @MockitoBean
    UserService users;

    @Test
    void returnsAnExistingUser() {
        when(users.find(1L)).thenReturn(Optional.of(new User(1L, "Ada")));

        assertThat(mvc.get().uri("/users/{id}", 1))
            .hasStatusOk()
            .hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
            .bodyJson()
            .extractingPath("$.name").isEqualTo("Ada");
    }

    @Test
    void unknownUserIsNotFound() {
        when(users.find(99L)).thenReturn(Optional.empty());

        assertThat(mvc.get().uri("/users/{id}", 99)).hasStatus(HttpStatus.NOT_FOUND);
    }
}

MockMvcTester (available since Spring Framework 6.2) is the AssertJ-style entry point: you write assertThat(mvc.get().uri(...)) and chain assertions, which fits the rest of an AssertJ test suite. The older MockMvc with static imports, mockMvc.perform(get("/users/1")).andExpect(status().isOk()), still works and you will see it in most existing projects. Both drive the same machinery, so everything in this lesson applies to either.

@MockitoBean replaces the real bean with a Mockito mock in the test's context. It supersedes @MockBean, which was deprecated and is removed in Boot 4. The mock starts with default answers (Optional.empty(), null, empty collections, zero), so you stub only what the test needs, and you can verify interactions afterwards with verify(users).create("Ada").

What the mini version does

Before the next real-world details, here is the whole pipeline in about 90 lines. The TryIt contains a tiny dispatcher (a controller that parses paths and JSON using the real Jackson library), a stub service, and a MockMvc class whose perform returns an object with andExpectStatus and andExpectJson methods. Every test builds a request, performs it and asserts, without any server.

Java A mini MockMvc over a mini dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the flow (build a request, dispatch, assert on status and JSON), the style of test, and Jackson. What is the stand-in: the dispatcher parses paths by hand, whereas Spring MVC does mapping, argument resolution, content negotiation, validation and exception handling with hundreds of classes. The last test fails on purpose to show the failure message.

Asserting on JSON

A response body is text, so assert on its structure rather than comparing whole strings, which break when field order or whitespace changes. With MockMvcTester the bodyJson() assertions use JsonPath expressions and AssertJ:

Java
assertThat(mvc.get().uri("/orders/7"))
    .hasStatusOk()
    .bodyJson()
    .hasPathSatisfying("$.lines", lines -> assertThat(lines).isNotNull())
    .extractingPath("$.lines[0].sku").isEqualTo("book-1");

For larger payloads, compare against a file with isLenientlyEqualTo(new ClassPathResource("order-7.json")): lenient comparison ignores extra fields and field order. The classic MockMvc style uses jsonPath("$.name").value("Ada") and content().json("{...}") for the same checks.

Test the error responses just as carefully as the happy path. Your clients depend on the shape of a 400 or 404 as much as on a 200:

Java
@Test
void rejectsABlankName() {
    assertThat(mvc.post().uri("/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""
                {"name": "  "}
                """))
        .hasStatus(HttpStatus.BAD_REQUEST)
        .bodyJson()
        .extractingPath("$.detail").asString().contains("name");
    verifyNoInteractions(users);
}

The verifyNoInteractions line is the point of the test: validation must stop the request before the service runs. It ties directly to Bean Validation and Error Handling and Problem Details: a web slice test is the cheapest place to prove that the pieces are connected.

Security in web tests

If Spring Security is on the classpath, @WebMvcTest includes its configuration, so every request is subject to your filter chain. A test without credentials gets 401, and a POST without a CSRF token gets 403, which surprises people the first time. Add spring-security-test and tell the test who is calling:

Java
@Test
@WithMockUser(roles = "ADMIN")
void adminCanDeleteUsers() {
    assertThat(mvc.delete().uri("/users/1").with(csrf())).hasStatus(HttpStatus.NO_CONTENT);
}

@Test
@WithMockUser(roles = "USER")
void ordinaryUsersCannotDeleteUsers() {
    assertThat(mvc.delete().uri("/users/1").with(csrf())).hasStatus(HttpStatus.FORBIDDEN);
}

@Test
void anonymousUsersAreAskedToLogIn() {
    assertThat(mvc.get().uri("/users/1")).hasStatus(HttpStatus.UNAUTHORIZED);
}

@WithMockUser puts an authenticated user into the security context without any real login, csrf() supplies a valid CSRF token (see CSRF, CORS and Secure Defaults), and jwt() does the equivalent for resource servers. Write one test per rule: allowed role, forbidden role, anonymous. These three lines are cheap insurance, and a missing @PreAuthorize is exactly what they catch.

The second TryIt models such a rule table. The filter decides 401, 403 or pass, from a user and the request, in the order Spring Security does: authenticate first, then authorize.

Java Who may call what: a tiny security filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: the order of the decisions (401 before 403, deny by default) and the idea of one test per rule. What is the stand-in: Spring Security expresses rules with authorizeHttpRequests, role hierarchies and method security, and its filter chain does far more than this single method.

Practical tips

  • Test the contract, not the framework. Do not assert that Jackson can serialize a string. Assert that your endpoint returns the field names your clients rely on.
  • One slice per controller. @WebMvcTest(UserController.class) keeps the context small and the cache effective; a bare @WebMvcTest loads every controller.
  • Do not mock what you own in the same layer. In a web test, mock the service. In a service test, do not start the web layer at all.
  • Add @Import for what the slice skips. Slices exclude plain @Component/@Configuration beans. If your controller needs a custom ObjectMapper module, a converter or your SecurityFilterChain, import them explicitly with @Import(SecurityConfig.class).
  • Prefer @SpringBootTest(webEnvironment = RANDOM_PORT) with a real HTTP client only for end-to-end checks. Boot 4 and Spring Framework 7 add RestTestClient, a fluent client that works against a live server, against a MockMvc setup, or against a single controller, so the same assertions can run at different rungs of the ladder.

If a web slice test fails with "No qualifying bean of type ..." the controller needs a bean the slice did not load. Add a @MockitoBean for it (the usual fix), or @Import it if it is real configuration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @WebMvcTest(OrderController.class) load?

    A web slice limits the context to the beans the web layer needs. Anything the controller depends on, such as services, must be supplied as mocks.
  2. 2. How do you give a controller under test a fake UserService?

    @MockitoBean replaces the bean in the test context with a Mockito mock, which you stub with when(...).thenReturn(...) and verify afterwards.
  3. 3. A test posts a blank name and the service must not be called. Which line proves that?

    Validation should reject the request before the controller method runs, so the mocked service must receive no calls.
  4. 4. A secured endpoint returns 403 in a test for a POST, even for a logged-in @WithMockUser. What is the most likely cause?

    With CSRF protection active, state-changing requests need a valid token. The spring-security-test helper csrf() supplies one for the test.
  5. 5. Why is asserting on JSON structure (JsonPath or lenient comparison) better than comparing the body to a full string?

    String equality breaks on irrelevant differences. Path-based or lenient checks pin down the contract and nothing more.

Summary

  • @WebMvcTest starts only the web layer, so controller tests run in about a second; MockMvc dispatches requests without a network port.
  • MockMvcTester gives AssertJ-style assertions, and the classic MockMvc with andExpect drives the same machinery.
  • Supply the controller's dependencies with @MockitoBean, stub what you need and verify interactions (or their absence).
  • Assert JSON by path or leniently, and test error responses as carefully as successes.
  • With Spring Security, test one case per rule: allowed role, forbidden role, anonymous, with @WithMockUser, csrf() and jwt().
  • Use @Import for web configuration the slice skips, and keep end-to-end checks for a few full-application tests.

Next: Integration Tests with Testcontainers.