Skip to content

Spring Boot Test Web Mvc

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot Test MockMvc Not Configuring. We cover key concepts, practical examples, and best practices.

The Problem

MockMvc returns 404 or the web context is not loaded.

Quick Fix

Use @WebMvcTest

Wrong:

@SpringBootTest
// Full context, not just web

Output:

Web context not specific

Right:

@WebMvcTest(UserController.class)
// Only loads controller

Output:

Controller layer only

Inject MockMvc

Wrong:

// MockMvc not injected

Output:

Cannot perform requests

Right:

@Autowired
private MockMvc mockMvc;

Output:

MockMvc injected

Mock dependencies

Wrong:

// @MockBean not used for services

Output:

Real service invoked

Right:

@MockBean
private UserService userService;

Output:

Service layer mocked

Prevention

  • Use @WebMvcTest for controller-level tests
  • Inject MockMvc with @Autowired
  • Use @MockBean for service dependencies

Common Mistakes with boot test web mvc

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Difference between @WebMvcTest and @SpringBootTest?

@WebMvcTest only loads controllers. @SpringBootTest loads the full context.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro