Introduction to MockMvc REST Controller Unit Testing

In the world of Spring Boot development, writing clean, testable, and maintainable code is key. Controllers are the entry point to your RESTful APIs and need to be thoroughly tested. That’s where MockMvc comes in β€” a powerful utility provided by the Spring Test module to simulate HTTP requests and verify responses.

In this post, we will walk you through everything you need to know about MockMvc REST Controller Unit Testing, from setup to practical examples.

Introduction to MockMvc REST Controller Unit Testing

βš™οΈ Project Setup

Make sure your project includes the following dependencies in your pom.xml:




    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    


spring-boot-starter-test includes JUnit 5, Mockito, and MockMvc support.

πŸ“ Package Structure


com.kscodes.springboot
β”œβ”€β”€ controller
β”‚   └── GreetingController.java
β”œβ”€β”€ service
β”‚   └── GreetingService.java
└── test
    └── controller
        └── GreetingControllerTest.java

πŸ’¬ Example Controller


package com.kscodes.springboot.controller;

import com.kscodes.springboot.service.GreetingService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/greet")
public class GreetingController {

    private final GreetingService greetingService;

    public GreetingController(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @GetMapping("/{name}")
    public String greet(@PathVariable String name) {
        return greetingService.greet(name);
    }
}

πŸ’‘ Greeting Service (Mocked in Tests)


package com.kscodes.springboot.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

πŸ§ͺ Unit Testing REST Controllers with MockMvc

βœ… Test Using @WebMvcTest and MockMvc


package com.kscodes.springboot.controller;

import com.kscodes.springboot.service.GreetingService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(GreetingController.class)
public class GreetingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GreetingService greetingService;

    @Test
    public void testGreetEndpoint() throws Exception {
        when(greetingService.greet("Ketan")).thenReturn("Hello, Ketan!");

        mockMvc.perform(get("/api/greet/Ketan"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, Ketan!"));
    }
}

This is a classic example of Unit Testing REST Controllers with MockMvc, isolating only the controller layer with a mocked service.

🧰 Key Points When Using MockMvc

  • @WebMvcTest loads only the controller-related components.
  • MockMvc allows HTTP-like request simulation.
  • @MockBean is used to replace Spring Beans with mocks.
  • Assertions can verify status, headers, body content, and more.

πŸ” Why Use MockMvc for REST Controller Testing?

  • No need to start a full web server.
  • Fast and efficient.
  • Provides HTTP request simulation with complete control.
  • Works seamlessly with JUnit and Mockito.

πŸ§ͺ More Tests (Edge Cases)

❌ Test Not Found Scenario


@Test
public void testGreetWithMissingParam() throws Exception {
    mockMvc.perform(get("/api/greet/"))
           .andExpect(status().isNotFound());
}

βœ… Test for Different Names


@Test
public void testDifferentNames() throws Exception {
    when(greetingService.greet("Alice")).thenReturn("Hello, Alice!");

    mockMvc.perform(get("/api/greet/Alice"))
           .andExpect(status().isOk())
           .andExpect(content().string("Hello, Alice!"));
}

πŸ“š Summary

In this tutorial, we covered how to perform Unit Testing REST Controllers with MockMvc using Spring Boot and JUnit 5. You have learned:

  • How to configure the @WebMvcTest
  • How to simulate the requests using MockMvc
  • How to mock the dependencies with @MockBean
  • How to assert on the status codes and response bodies

MockMvc REST Controller Unit Testing is a fundamental skill for Spring Boot developers. It allows you to thoroughly test your API endpoints in isolation, ensuring they function correctly and handle various scenarios before the application is deployed to production. By simulating HTTP requests and responses, MockMvc helps validate business logic, input validation, error handling, and controller behaviorβ€”providing confidence that your RESTful services are reliable, robust, and ready for real-world usage.