tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Microservices > Spring Boot > Spring Boot REST API Testing with MockMvc

Spring Boot REST API Testing with MockMvc

Author: Venkata Sudhakar

Testing Spring Boot REST controllers with MockMvc lets you verify your API endpoints - HTTP status codes, response bodies, headers, and error handling - without starting a full web server. @WebMvcTest loads only the web layer (controllers, filters, security) and none of the service or repository beans, making tests fast and focused. You inject MockMvc into your test and use it to perform GET, POST, PUT, and DELETE requests, then assert on the response using a fluent API.

Since @WebMvcTest does not load service beans, you mock your service dependencies using @MockBean. This isolates the controller test from business logic - you test that the controller correctly maps HTTP requests to service calls and correctly maps service results to HTTP responses. For full integration tests that test the entire stack including the database, use @SpringBootTest with TestRestTemplate or WebTestClient instead.

The below example shows a controller test for an order API that verifies a GET request returns the correct JSON and a POST request creates an order and returns 201 Created.


It gives the following output,

[INFO] Running OrderControllerTest

GET /api/orders/1001
  Status: 200 OK
  Body: {"id":1001,"status":"CREATED","amount":149.99}
  -> PASS

GET /api/orders/9999
  Status: 404 Not Found
  Body: {"message":"Order 9999 not found"}
  -> PASS

Tests run: 2, Failures: 0, Errors: 0 -- Time elapsed: 0.8s

It gives the following output,

POST /api/orders  body={"amount":299.99,"customerId":500}
  Status: 201 Created
  Header: Location: /api/orders/1002
  Body: {"id":1002,"status":"CREATED","amount":299.99}
  -> PASS

POST /api/orders  body={"amount":-10.0,"customerId":500}
  Status: 400 Bad Request
  Body: {"errors":["amount must be positive"]}
  -> PASS

Tests run: 4, Failures: 0, Errors: 0 -- Time elapsed: 0.9s

MockMvc test coverage checklist for every REST endpoint: test the happy path (2xx response with correct body), test not found (404), test validation errors (400 with error details), and test any authentication/authorization rules (401 or 403). Keep @WebMvcTest tests focused on the HTTP layer only - business logic belongs in separate service unit tests, not in controller tests. A full @SpringBootTest integration test that hits a real database is valuable but slow - run it in CI, not on every local build.


 
  


  
bl  br