0
0
JUnittesting~7 mins

@WebMvcTest for controller testing in JUnit

Choose your learning style9 modes available
Introduction

@WebMvcTest helps test only the web layer of your application, like controllers, without starting the full app. It makes tests faster and focused.

When you want to check if your controller handles HTTP requests correctly.
When you want to test controller methods without loading services or repositories.
When you want to verify the HTTP status and response content from your controller.
When you want to test controller behavior with mock dependencies.
When you want to isolate controller tests from other layers for faster feedback.
Syntax
JUnit
@WebMvcTest(ControllerClass.class)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private SomeService someService;

    @Test
    public void testControllerMethod() throws Exception {
        mockMvc.perform(get("/endpoint"))
               .andExpect(status().isOk())
               .andExpect(content().string("expected response"));
    }
}

@WebMvcTest loads only the controller and related MVC components, not the full Spring context.

Use @MockBean to provide mock implementations for service dependencies.

Examples
Simple test for a controller that returns "Hello World" on /hello endpoint.
JUnit
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnHello() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello World"));
    }
}
Test with a mocked service to control the response returned by the controller.
JUnit
@WebMvcTest(UserController.class)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void shouldReturnUserName() throws Exception {
        when(userService.getUserName()).thenReturn("Alice");

        mockMvc.perform(get("/username"))
               .andExpect(status().isOk())
               .andExpect(content().string("Alice"));
    }
}
Sample Program

This test checks the /greet endpoint of GreetingController. The GreetingService is mocked to return "Hello Test". The test verifies the HTTP status is 200 OK and the response body matches the mocked string.

JUnit
package com.example.demo;

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

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;

@WebMvcTest(GreetingController.class)
public class GreetingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GreetingService greetingService;

    @Test
    public void testGreeting() throws Exception {
        when(greetingService.greet()).thenReturn("Hello Test");

        mockMvc.perform(get("/greet"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello Test"));
    }
}

// Controller class
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private final GreetingService greetingService;

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

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

// Service interface
package com.example.demo;

public interface GreetingService {
    String greet();
}
OutputSuccess
Important Notes

Always mock service dependencies to keep controller tests isolated.

Use MockMvc to simulate HTTP requests and check responses without starting a server.

@WebMvcTest does not load security or database layers unless explicitly configured.

Summary

@WebMvcTest focuses on testing Spring MVC controllers only.

MockMvc helps simulate HTTP calls and verify responses.

Mock dependencies with @MockBean to isolate controller logic.