Testing controllers with @WebMvcTest
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Before every release someone must check that GET /products/6 answers 200 and a missing product answers 404. Doing it by hand, with a real server and database, is slow and easy to forget.
A slice test loads only the web layer
A slice test starts only one layer of the application. @WebMvcTest(ProductController.class) builds a context with Spring MVC, Jackson, error handling and that one controller; services and data sources are not created.
A controller test should not need a database. The example lists the beans that a @WebMvcTest slice contains.
Example 1 · SliceBeansTest.java: what a slice contains
Runs in: the rest-lab practice project (Spring Boot 4.1), src/test/java
// src/test/java/com/shoplite/lab/product/SliceBeansTest.javapackage com.shoplite.lab.product;
import static org.mockito.Mockito.mockingDetails;
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.ApplicationContext;import org.springframework.test.context.bean.override.mockito.MockitoBean;
@WebMvcTest(ProductController.class)class SliceBeansTest {
@Autowired private ApplicationContext context;
@MockitoBean private ProductService productService;
@Test void showWhatTheSliceContains() { System.out.println("Beans in the @WebMvcTest slice: " + context.getBeanDefinitionCount()); System.out.println("productService is a Mockito mock: " + mockingDetails(productService).isMock()); }}$ mvnw test -Dtest=SliceBeansTest ... Beans in the @WebMvcTest slice: 109 productService is a Mockito mock: true [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.186 s -- in com.shoplite.lab.product.SliceBeansTest
What this code does
@WebMvcTest(ProductController.class)creates the web layer and only this controller; the full app context of the same project has 152 beans (Example 5).productServiceis not the realProductServicebut a Mockito mock, because of@MockitoBean. The real class, with its in-memory products, is never created.- Bean counts and times differ with the Boot version and your computer. On Windows, run
mvnw.cmd test -Dtest=SliceBeansTest.
A test that starts everything (@SpringBootTest) also starts what the controller does not need: in ShopLite that soon means a MySQL connection pool, which needs a running database just to check a status code. The slice tests one thing: does the controller map HTTP to service calls and answers correctly?
The test dependency is already in the project: Spring Initializr adds spring-boot-starter-webmvc-test (JUnit 5, AssertJ, Mockito and Spring's test support) with test scope. Test classes go under src/test/java in the same package as the class they test, and mvnw test runs them all.
WARNING: lines. They are warnings about a future JDK, not test failures.Replacing the service with @MockitoBean
@MockitoBean on a test field puts a mock of that type into the Spring context: a fake object made by Mockito that does nothing until the test says what it should return.
The controller needs a ProductService, but the slice does not create one. The example forgets @MockitoBean and shows the failure.
Example 2 · NoMockTest.java: forgetting @MockitoBean
Runs in: the rest-lab practice project (Spring Boot 4.1), src/test/java
// src/test/java/com/shoplite/lab/product/NoMockTest.javapackage com.shoplite.lab.product;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(ProductController.class)class NoMockTest {
@Autowired private MockMvcTester mvc;
@Test void getProduct() { assertThat(mvc.get().uri("/api/v1/products/6")).hasStatusOk(); }}*************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.shoplite.lab.product.ProductController required a bean of type 'com.shoplite.lab.product.ProductService' that could not be found. Action: Consider defining a bean of type 'com.shoplite.lab.product.ProductService' in your configuration. java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@5ebffb44 testClass = com.shoplite.lab.product.NoMockTest, ...] [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
What this code does
- The slice creates
ProductController, whose constructor needs aProductService. Services are not part of the slice, so Spring cannot build the controller and the test errors before it runs. - The fix is one field:
@MockitoBean private ProductService productService;. Every dependency of the controller under test needs a mock (or an@Importof a real bean). - The report is an Error, not a Failure: the test could not even start, so no assertion ran.
given(productService.findById(6)).willReturn(Optional.of(AIRDOPES)) scripts one answer. The test can now reach every branch of the controller on purpose: a found product, a missing one, a failed delete. verify(productService).delete(16) checks that the controller really called the service with the right id.
@MockitoBean (package org.springframework.test.context.bean.override.mockito) replaced the older @MockBean, which Spring Boot 4 removed. Forget it, and the slice cannot create the controller at all: the test fails with the same "required a bean of type ... that could not be found" report you met in the DI module.
Fix the error
Fix the test setup
The slice test cannot start. Pick the line that fixes the field.
The controller needs a ProductService, and the slice has none.
Error
Parameter 0 of constructor in ProductController required a bean of type 'ProductService' that could not be found.
MockMvcTester: performing requests and asserting the response
MockMvcTester sends a request through Spring MVC in memory, with no network and no port, and opens AssertJ checks on the response. Spring Framework 6.2 added it.
To test an endpoint, send a request and check the answer: status, headers and JSON. The example has six tests for six outcomes.
Example 3 · ProductControllerTest.java: six tests for six outcomes
Runs in: the rest-lab practice project (Spring Boot 4.1), src/test/java
package com.shoplite.lab.product;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;
import java.math.BigDecimal;import java.util.Optional;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(ProductController.class)class ProductControllerTest {
private static final ProductResponse AIRDOPES = new ProductResponse(6, "ACC-AD141", "boAt Airdopes 141", 4, "Accessories", new BigDecimal("1299.00"), 120, true);
@Autowired private MockMvcTester mvc;
@MockitoBean private ProductService productService;
@Test void getReturnsTheProductAsJson() { given(productService.findById(6)).willReturn(Optional.of(AIRDOPES));
assertThat(mvc.get().uri("/api/v1/products/6")) .hasStatusOk() .hasContentType(MediaType.APPLICATION_JSON) .bodyJson().isLenientlyEqualTo(""" {"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","price":1299.00,"isActive":true}"""); }
@Test void getUnknownProductIs404() { given(productService.findById(99)).willReturn(Optional.empty());
assertThat(mvc.get().uri("/api/v1/products/99")) .hasStatus(HttpStatus.NOT_FOUND); }
@Test void createReturns201WithLocationAndBody() { ProductResponse keyboard = new ProductResponse(16, "ACC-KB100", "Zebronics Wireless Keyboard", 4, "Accessories", new BigDecimal("999.00"), 30, true); given(productService.create(any(CreateProductRequest.class))).willReturn(keyboard);
assertThat(mvc.post().uri("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) .content(""" {"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}""")) .hasStatus(HttpStatus.CREATED) .hasHeader("Location", "http://localhost/api/v1/products/16") .bodyJson().extractingPath("$.id").isEqualTo(16); }
@Test void deleteReturns204AndCallsTheService() { given(productService.delete(16)).willReturn(true);
assertThat(mvc.delete().uri("/api/v1/products/16")) .hasStatus(HttpStatus.NO_CONTENT); verify(productService).delete(16); }
@Test void deleteUnknownProductIs404() { given(productService.delete(99)).willReturn(false);
assertThat(mvc.delete().uri("/api/v1/products/99")) .hasStatus(HttpStatus.NOT_FOUND); }
@Test void textBodyIs415AndNeverReachesTheService() { assertThat(mvc.post().uri("/api/v1/products") .contentType(MediaType.TEXT_PLAIN) .content("Zebronics Keyboard")) .hasStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE); verifyNoInteractions(productService); }}$ mvnw test -Dtest=ProductControllerTest ... 2026-10-16T11:07:53.354+05:30 WARN 24212 --- [rest-lab] [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'text/plain' is not supported] [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.55 s -- in com.shoplite.lab.product.ProductControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
getReturnsTheProductAsJsonscripts the mock, sendsGET /api/v1/products/6, then checks 200, the JSON content type and the listed fields withisLenientlyEqualTo(the other fields are ignored).- The 201 test checks the status, the full
Locationvalue (http://localhost/...in a slice) and the id from the mock's answer. The 204 test alsoverifys the service call; the 415 test proves the service was never touched. - The
WARNline comes from the 415 test: Spring logs it exactly as in a running app. Text blocks (""") keep the JSON readable; they are standard Java since version 15.
mvc.get().uri("/api/v1/products/6") builds the request, and assertThat(...) performs it. Older tutorials use MockMvc with perform(...).andExpect(...), which does the same in a less readable style. The checks read like the response: .hasStatusOk() or .hasStatus(HttpStatus.NOT_FOUND), .hasContentType(MediaType.APPLICATION_JSON), .hasHeader("Location", "..."), and .bodyJson() for the JSON. bodyJson().extractingPath("$.name") reads one field; bodyJson().isLenientlyEqualTo("{...}") compares the fields you list and ignores the others.
The request is fully real to the controller: path variables, query parameters, @RequestBody JSON with the strict Jackson settings from application.properties, consumes and produces. So 400, 405 and 415 can be tested too.
Testing 201 with Location, 204 and 404 paths
A test per outcome is the rule that every status code the contract promises for an endpoint gets its own small test method: 201 with Location, 204, 404 and the rest.
Each outcome of an endpoint is a promise to the client. The examples test 201, 204 and 404, and show how a failing test reads.
Example 4 · WrongStatusTest.java: reading a failing test
Runs in: the rest-lab practice project (Spring Boot 4.1), src/test/java
// src/test/java/com/shoplite/lab/product/WrongStatusTest.javapackage com.shoplite.lab.product;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(ProductController.class)class WrongStatusTest {
@Autowired private MockMvcTester mvc;
@MockitoBean private ProductService productService;
@Test void createReturnsTheProduct() { given(productService.create(any(CreateProductRequest.class))).willReturn(new ProductResponse(16, "ACC-KB100", "Zebronics Wireless Keyboard", 4, "Accessories", new BigDecimal("999.00"), 30, true));
assertThat(mvc.post().uri("/api/v1/products") .contentType(MediaType.APPLICATION_JSON) .content(""" {"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}""")) .hasStatusOk() .bodyJson().extractingPath("$.price").isEqualTo(999.00); }}MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/v1/products
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"97"]
Body = {"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}
Session Attrs = {}
Handler:
Type = com.shoplite.lab.product.ProductController
Method = com.shoplite.lab.product.ProductController#create(CreateProductRequest)
...
MockHttpServletResponse:
Status = 201
Error message = null
Headers = [Location:"http://localhost/api/v1/products/16", Content-Type:"application/json"]
Content type = application/json
Body = {"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
Forwarded URL = null
Redirected URL = http://localhost/api/v1/products/16
Cookies = []
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 12.41 s <<< FAILURE! -- in com.shoplite.lab.product.WrongStatusTest
[ERROR] com.shoplite.lab.product.WrongStatusTest.createReturnsTheProduct -- Time elapsed: 1.241 s <<< FAILURE!
org.opentest4j.AssertionFailedError:
[HTTP status code]
expected: 200
but was: 201What this code does
- The test expects 200 for a create, but the controller correctly answers 201. Here the test is wrong, not the code: fix it to
.hasStatus(HttpStatus.CREATED), and it passes (the price checkisEqualTo(999.00)already does). - The print shows everything needed to decide that: the request that was sent, which controller method handled it, and the full response with its
Locationheader. - "Redirected URL" is how the mock response reports any
Locationheader; nothing was redirected.
In a slice test the server name is localhost with no port, so the expected header is http://localhost/api/v1/products/16. The id comes from the mock's answer, which proves the controller used the service result to build the URL.
When a check fails, MockMvcTester prints the whole exchange: the request (method, URI, headers, body), the handler method that ran, and the response (status, headers, body). Read that print before changing any code: it usually shows the cause at once.
Predict the output
Predict the assertion
Predict what MockMvcTester sees in these controller tests.
Round 1 of 2
What is the Location header after the create?
Why slice tests beat starting the whole app for controller checks
@SpringBootTest starts the whole application context, with every bean. It answers "do all the parts work together?", and needs everything the app needs, such as a database.
Starting the whole application just to check a status code costs time and needs a database. The example runs a check with the full context for comparison.
Example 5 · FullAppTest.java: the whole context for comparison
Runs in: the rest-lab practice project (Spring Boot 4.1), src/test/java
// src/test/java/com/shoplite/lab/product/FullAppTest.javapackage com.shoplite.lab.product;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.context.ApplicationContext;import org.springframework.test.web.servlet.assertj.MockMvcTester;
@SpringBootTest // the whole application context@AutoConfigureMockMvcclass FullAppTest {
@Autowired private MockMvcTester mvc;
@Autowired private ApplicationContext context;
@Test void getUsesTheRealService() { System.out.println("Beans in the full context: " + context.getBeanDefinitionCount()); assertThat(mvc.get().uri("/api/v1/products/6")) .hasStatusOk() .bodyJson().extractingPath("$.name").isEqualTo("boAt Airdopes 141"); }}$ mvnw test -Dtest=FullAppTest Started FullAppTest in 6.26 seconds (process running for 9.9) Beans in the full context: 152 [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 11.61 s -- in com.shoplite.lab.product.FullAppTest $ mvnw test -Dtest=ProductControllerTest Started ProductControllerTest in 7.263 seconds (process running for 10.532) [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.05 s -- in com.shoplite.lab.product.ProductControllerTest
What this code does
- The full test uses the real
ProductServiceand its seed data, so it can only check what that data happens to contain; the slice test chose its data through the mock. - In this tiny lab both start in 6 to 8 seconds on a laptop, and the slice is not faster yet: Mockito's own start-up costs about as much as the 43 extra beans. Once ShopLite connects to MySQL, the full context needs a running database and starts the pool; the slice still needs neither.
- Each
mvnw test -Dtest=...here is a new JVM, so the times include JVM start-up. In onemvnw testrun, test classes with the same setup share one cached context.
In this tiny lab both kinds start in a few seconds, mostly JVM and Mockito start-up; the full context has 152 beans against 109 in the slice. The gap grows with the app: the full context will also start a connection pool, migrations and security, while the controller slice never will. Spring also caches a test context and reuses it for test classes with the same setup.
The usual mix: many fast slice tests for controllers (every status code), plain unit tests for services, and a few @SpringBootTest tests that run the real path end to end. The final ShopLite release adds one such smoke test.
Next step
Check your understanding
12 quick questions