@WebMvcTest and MockMvc for controllers
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's controllers return JSON, status codes and error bodies. Starting the whole app and MySQL to check one URL is slow, so tests get skipped. How do you test only the web layer?
Test starters in Spring Boot 4
A test starter is a dependency bundle that adds the libraries for one kind of test, such as JUnit and Mockito. Spring Boot manages their versions, and the dependency goes in test scope so it never ships in the jar.
Add the test starters to pom.xml, each in test scope. Every starter brings the libraries for one kind of test.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webmvc-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security-test</artifactId> <scope>test</scope></dependency>spring-boot-starter-test brings JUnit Jupiter, Mockito, AssertJ, Hamcrest, JsonPath and Spring's own spring-test.
Boot 4 splits the slice support by technology. spring-boot-starter-webmvc-test adds @WebMvcTest and MockMvc (and includes spring-boot-starter-test), and the JPA and security starters do the same for their parts. ShopLite's pom has all three.
spring-boot-starter-test, and @WebMvcTest lived in org.springframework.boot.test.autoconfigure.web.servlet. In Boot 4 the import is org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest.@WebMvcTest(ProductController.class) loads only the web layer
A test slice is a small Spring test context that loads only one layer of the app, such as the web layer. It starts fast and needs no database, because the other layers are left out or replaced by mocks.
Start only the web layer of ShopLite and call it in memory. Example 1 builds a tiny dispatcher in plain Java to show the idea: find the handler for a URL, call it, check the answer.
Example 1 · A tiny dispatcher: requests without a server
import java.util.Map;
record Response(int status, String contentType, String body) {}
class ResourceNotFoundException extends RuntimeException { ResourceNotFoundException(String resource, int id) { super(resource + " " + id + " was not found."); }}
/** The service the controller calls. In the test it is a stand-in with fixed answers, like a mock. */interface CategoryService { String get(int id);}
/** The controller: HTTP in and out only. */class CategoryController { private final CategoryService service;
CategoryController(CategoryService service) { this.service = service; }
Response get(int id) { return new Response(200, "application/json", service.get(id)); }}
/** A tiny DispatcherServlet: finds the handler for a URL and turns exceptions into problem JSON. */class Dispatcher { private final CategoryController controller;
Dispatcher(CategoryController controller) { this.controller = controller; }
Response perform(String method, String path) { String prefix = "/api/v1/categories/"; if (!method.equals("GET") || !path.startsWith(prefix)) { return new Response(404, "application/problem+json", "{\"title\":\"Resource not found\"}"); } try { return controller.get(Integer.parseInt(path.substring(prefix.length()))); } catch (ResourceNotFoundException e) { // the global exception handler's job return new Response(404, "application/problem+json", "{\"title\":\"Resource not found\",\"detail\":\"" + e.getMessage() + "\"}"); } }}
public class MiniMockMvcDemo { static void expect(String what, Object expected, Object actual) { System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + what + (expected.equals(actual) ? "" : ": expected " + expected + " but was " + actual)); }
public static void main(String[] args) { Map<Integer, String> answers = Map.of(2, "{\"id\":2,\"name\":\"Mobiles\",\"parentId\":1}"); CategoryService stub = id -> { if (!answers.containsKey(id)) { throw new ResourceNotFoundException("Category", id); } return answers.get(id); }; Dispatcher mvc = new Dispatcher(new CategoryController(stub)); // no server, no port, no network
Response ok = mvc.perform("GET", "/api/v1/categories/2"); System.out.println("GET /api/v1/categories/2 -> " + ok.status() + " " + ok.body()); expect("status 200", 200, ok.status()); expect("body has name Mobiles", true, ok.body().contains("\"name\":\"Mobiles\""));
Response missing = mvc.perform("GET", "/api/v1/categories/99"); System.out.println("GET /api/v1/categories/99 -> " + missing.status() + " " + missing.body()); expect("status 404", 404, missing.status()); expect("problem content type", "application/problem+json", missing.contentType()); }}GET /api/v1/categories/2 -> 200 {"id":2,"name":"Mobiles","parentId":1}
PASS status 200
PASS body has name Mobiles
GET /api/v1/categories/99 -> 404 {"title":"Resource not found","detail":"Category 99 was not found."}
PASS status 404
PASS problem content typeWhat this code does
Dispatcher.performplays MockMvc: it finds the handler for the URL and calls it in memory. No socket is opened.- The service is a stand-in with fixed answers, like a
@MockitoBean. For id 99 it throws, and the dispatcher turns that into a 404 problem body, the job ofGlobalExceptionHandler. - The checks look at status, content type and body: exactly what
status(),content()andjsonPath()do in a real MockMvc test.
@WebMvcTest(CategoryController.class) loads Spring MVC, the named controller, every @RestControllerAdvice (ShopLite's GlobalExceptionHandler), Jackson, Bean Validation and converters. It does not create services, repositories, a DataSource or your own @Configuration classes.
SecurityConfig is a @Configuration class, so the slice skips it and Boot's default security (every request needs a login) applies. ShopLite's web tests add @Import(OpenWebMvcTestSecurity.class), which permits every request. Security rules get their own tests later in this module.
@MockitoBean replaces the service
@MockitoBean is a Spring test annotation that replaces a bean in the test context with a Mockito mock. You script its answers with given(...), and Spring resets it after each test.
The controller's constructor needs a CategoryService, and the slice has none. One annotation puts a mock in that slot.
@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryControllerTest {
@Autowired private MockMvc mockMvc;
@MockitoBean // a mock bean replaces the real service private CategoryService categoryService;}You stub it as in any Mockito test: given(categoryService.get(2)).willReturn(...). Spring resets the mock after each test, so one test's stubs never leak into the next.
@MockBean from org.springframework.boot.test.mock.mockito was deprecated in Boot 3.4 and removed in Boot 4. Use org.springframework.test.context.bean.override.mockito.MockitoBean.
mockMvc.perform(get(...)) with status() and jsonPath()
MockMvc is Spring's test client. It sends a request to the DispatcherServlet in memory, with no Tomcat, port or network, and lets you check the status, headers and JSON body of the response.
Send one request and check what comes back. Example 2 uses the classic MockMvc style; Example 3 shows the same test in the newer AssertJ style, MockMvcTester.
Example 2 · src/test/java/com/shoplite/category/CategoryControllerTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.category;
import static org.hamcrest.Matchers.hasSize;import static org.hamcrest.Matchers.nullValue;import static org.mockito.BDDMockito.given;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.jsonPath;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.MockMvc;
import com.shoplite.common.OpenWebMvcTestSecurity;import com.shoplite.common.ResourceNotFoundException;
/** The category endpoints' HTTP side: Spring MVC and JSON are real, the service is a mock. */@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class) // permit all: security has its own testsclass CategoryControllerTest {
@Autowired private MockMvc mockMvc;
@MockitoBean private CategoryService categoryService;
@Test void listReturnsEveryCategory() throws Exception { given(categoryService.findAll()).willReturn(List.of( new CategoryResponse(1, "Electronics", null), new CategoryResponse(2, "Mobiles", 1)));
mockMvc.perform(get("/api/v1/categories")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].parentId").value(nullValue())) .andExpect(jsonPath("$[1].name").value("Mobiles")) .andExpect(jsonPath("$[1].parentId").value(1)); }
@Test void getReturnsOneCategory() throws Exception { given(categoryService.get(2)).willReturn(new CategoryResponse(2, "Mobiles", 1));
mockMvc.perform(get("/api/v1/categories/2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").value(2)) .andExpect(jsonPath("$.name").value("Mobiles")); }
@Test void missingCategoryIs404() throws Exception { given(categoryService.get(99)).willThrow(new ResourceNotFoundException("Category", 99));
mockMvc.perform(get("/api/v1/categories/99")) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.title").value("Resource not found")); }}$ ./mvnw test -Dtest=CategoryControllerTest ... [INFO] Running com.shoplite.category.CategoryControllerTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.906 s -- in com.shoplite.category.CategoryControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS If the controller answered 404 for category 2, the test would fail with: java.lang.AssertionError: Status expected:<200> but was:<404>
What this code does
@WebMvcTest(CategoryController.class)+@MockitoBean CategoryService: real MVC, real Jackson, real exception handler, fake service.jsonPath("$", hasSize(2))checks the array length;nullValue()checks that a top-level category is sent as"parentId": null, as the contract requires.- The third test proves the wiring from
ResourceNotFoundExceptionto a 404 ProblemDetail. The failure line shows the message you get when a status is wrong.
Example 3 · src/test/java/com/shoplite/category/CategoryControllerTesterTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.category;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.BDDMockito.given;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
import com.shoplite.common.OpenWebMvcTestSecurity;
/** The same check in the AssertJ style that ShopLite's existing controller tests use. */@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryControllerTesterTest {
@Autowired private MockMvcTester mvc;
@MockitoBean private CategoryService categoryService;
@Test void getReturnsOneCategory() { given(categoryService.get(2)).willReturn(new CategoryResponse(2, "Mobiles", 1));
assertThat(mvc.get().uri("/api/v1/categories/2")) .hasStatusOk() .bodyJson().isLenientlyEqualTo(""" {"id": 2, "name": "Mobiles", "parentId": 1} """); }}[INFO] Running com.shoplite.category.CategoryControllerTesterTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.161 s -- in com.shoplite.category.CategoryControllerTesterTest
What this code does
MockMvcTesteris autowired likeMockMvc.assertThat(...)runs the request;hasStatusOk()andbodyJson()are AssertJ checks.isLenientlyEqualTocompares the whole body but allows extra fields and any field order, so the test does not break when v1 adds a field.- The test takes about 0.2 s because Spring reuses the cached web context from the previous test class (same slice setup).
mockMvc.perform(get("/api/v1/categories/2")) sends the request. Each .andExpect(...) checks one thing: status().isOk(), content().contentType(...) or jsonPath("$.name").value("Mobiles"). A JSON path points into the body: $ is the whole document, $.name a field, $[1].name the second item's name, $[*].name every name.
ShopLite's existing tests use MockMvcTester: assertThat(mvc.get().uri(...)).hasStatusOk().bodyJson().... Both styles run the same request; use one style per project.
Predict the output
Read the JSON path
Pick what each path points to, or whether the check passes.
Round 1 of 3
Which value does this path select?
Why a test fails with 'No qualifying bean' and how to fix it
No qualifying bean is the Spring error for a bean that needs a dependency the context did not create. In a @WebMvcTest it usually means a controller whose service has no @MockitoBean.
Forget the mock and the slice cannot build the controller. Example 4 shows the real error; Example 5 builds a mini container in plain Java that fails the same way.
Example 4 · Forgetting the @MockitoBean
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryControllerTest {
@Autowired private MockMvc mockMvc;
// forgot: @MockitoBean private CategoryService categoryService;
@Test void getReturnsOneCategory() throws Exception { ... }
@Test void missingCategoryIs404() throws Exception { ... }}[ERROR] Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 3.021 s <<< FAILURE! -- in com.shoplite.category.CategoryControllerTest
[ERROR] com.shoplite.category.CategoryControllerTest.getReturnsOneCategory -- Time elapsed: 0.006 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@5a1c3cb4 testClass = com.shoplite.category.CategoryControllerTest, ...]
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryController' defined in file [...\target\classes\com\shoplite\category\CategoryController.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.shoplite.category.CategoryService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
[ERROR] com.shoplite.category.CategoryControllerTest.missingCategoryIs404 -- Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: ApplicationContext failure threshold (1) exceeded: skipping repeated attempt to load context for [WebMergedContextConfiguration@5a1c3cb4 testClass = com.shoplite.category.CategoryControllerTest, ...]What this code does
- The slice tried to build
categoryController; its constructor parameter 0 is aCategoryService, and nothing in the slice provides one. - Spring 7 tries the broken context once. Later tests in the class fail fast with "failure threshold (1) exceeded" instead of retrying.
- The fix is one line:
@MockitoBean private CategoryService categoryService;.
Example 5 · A mini container: why the slice needs the mock
import java.lang.reflect.Constructor;import java.util.HashMap;import java.util.Map;
interface CategoryService { String get(int id);}
class CategoryController { private final CategoryService service;
CategoryController(CategoryService service) { this.service = service; }
String get(int id) { return service.get(id); }}
/** A very small container: it builds a class by filling its constructor from the beans it has. */class MiniContainer { private final Map<Class<?>, Object> beans = new HashMap<>();
<T> void register(Class<T> type, T bean) { beans.put(type, bean); }
Object create(Class<?> type) throws Exception { Constructor<?> constructor = type.getDeclaredConstructors()[0]; Class<?>[] needed = constructor.getParameterTypes(); Object[] args = new Object[needed.length]; for (int i = 0; i < needed.length; i++) { args[i] = beans.get(needed[i]); if (args[i] == null) { throw new IllegalStateException("Error creating bean '" + type.getSimpleName() + "': No qualifying bean of type '" + needed[i].getSimpleName() + "' available"); } } return constructor.newInstance(args); }}
public class MiniContainerDemo { public static void main(String[] args) throws Exception { // Like @WebMvcTest(CategoryController.class): the controller is loaded, the service is not MiniContainer slice = new MiniContainer(); try { slice.create(CategoryController.class); } catch (IllegalStateException e) { System.out.println("Without a mock: " + e.getMessage()); }
// Like @MockitoBean CategoryService: a stand-in bean of the needed type is added slice.register(CategoryService.class, id -> "{\"id\":" + id + ",\"name\":\"Mobiles\",\"parentId\":1}"); CategoryController controller = (CategoryController) slice.create(CategoryController.class); System.out.println("With a mock: " + controller.get(2)); }}Without a mock: Error creating bean 'CategoryController': No qualifying bean of type 'CategoryService' available
With a mock: {"id":2,"name":"Mobiles","parentId":1}What this code does
MiniContainer.createfills a constructor from the beans it has, like Spring does. Without aCategoryServiceit fails with a 'No qualifying bean' message.- Registering a stand-in of the needed type, which is what
@MockitoBeandoes, lets the controller be created. - Real Spring adds more detail (bean name, parameter index, file), but the cause is the same.
Read the message from the bottom Caused by: it names the bean that failed (categoryController) and the type it needs. Add one @MockitoBean per constructor dependency of every controller in the slice.
@WebMvcTest with no class named loads every controller in the app, and then every service needs a mock. Name the controller you are testing to keep the slice small.
Fix the error
Fix the slice
The test fails when the class starts. Pick the line that fixes it.
Which replacement for line 4 fixes the error?
Error
No qualifying bean of type 'com.shoplite.category.CategoryService' available
Next step
Check your understanding
11 quick questions