Hello! Welcome back.
In our last lesson, we established a solid foundation for unit testing in Java by testing our PostService in complete isolation. You learned how to use JUnit 5 and Mockito to mock dependencies, control their behavior, and verify interactions—skills directly comparable to your experience with Jest.
Today, we move one layer up the stack to the web layer. Our goal is to test a REST controller in isolation using @WebMvcTest with mocked service dependencies. We'll focus on verifying that our controller correctly handles HTTP requests, deserializes request bodies, calls the appropriate service methods, and serializes the responses—all without involving a real database or a running web server.
Why Test Controllers Separately?
While the service layer contains the core business logic, the controller has its own distinct set of responsibilities related to the web layer. A simple unit test like the one we wrote for the service can't verify these.
To understand what we need to test, let's consult a clear breakdown of a controller's duties.
Testing MVC Web Controllers with Spring Boot and @WebMvcTest
The article "Testing MVC Web Controllers with Spring Boot and @WebMvcTest" by Tom Hombergs provides an excellent list of a controller's responsibilities. Understanding these is key to writing meaningful controller tests.
Read the sections titled "Responsibilities of a Web Controller" and "Unit or Integration Test?". Pay close attention to the table that lists what a simple unit test can and cannot cover. This will clarify why we need a different approach for testing controllers.
As you can see, a simple unit test misses critical aspects like HTTP request mapping, input/output serialization, and validation. To test these, we need to involve the Spring MVC framework, but we still want to keep the test isolated from the service and repository layers. This is precisely what @WebMvcTest is designed for.
MERN-to-Spring Mapping: supertest vs. MockMvc
In your MERN/Express background, you've likely used libraries like supertest in combination with Jest to make HTTP requests to your running application or a mock server to test your API endpoints.
Spring's approach is analogous. We use MockMvc to perform mock HTTP requests against our controller, and JUnit (along with Mockito) to write the assertions.

The key idea is the same: simulate HTTP interactions to test the web layer.
The Spring Way: @WebMvcTest and MockMvc
To achieve this isolated controller testing, we use two main tools:
-
@WebMvcTest: This annotation tells Spring Boot to set up a special, lightweight application context that contains only the beans related to the web layer. This includes your controllers, JSON converters (ObjectMapper), exception handlers (@ControllerAdvice), and the Spring MVC infrastructure itself. It specifically does not load@Service,@Repository, or@Componentbeans, keeping the test fast and focused. -
@MockBean: Since@WebMvcTestdoesn't load our service beans, how does the controller get its dependencies? We use@MockBean. This annotation creates a Mockito mock of a specific bean (like ourPostService) and registers it in the Spring application context. Any component that depends on that bean will be injected with this mock instead of the real one.- Key Distinction: In the last lesson, you used
@Mockfor a pure Mockito/JUnit test. Use@MockBeanwhen you are running a Spring-context-aware test (like with@WebMvcTestor@SpringBootTest) and need to replace a bean in that context.
- Key Distinction: In the last lesson, you used
-
MockMvc: This is the main entry point for our tests. It's a powerful utility that lets us "perform" mock HTTP requests (GET, POST, etc.) against our controller and then write expectations (assertions) against the result.
The following video provides a great visual demonstration of setting up a test with these components.
Spring Boot Testing Basics: How to Unit Test & Integration Test REST Controllers
This video from Dan Vega shows how to transform a simple unit test into an isolated integration test for a controller using @WebMvcTest and MockMvc.
Watch from 09:08 to 16:09. Focus on the annotations used (@WebMvcTest, @Autowired for MockMvc), and how mockMvc.perform() is used to make a GET request and andExpect() is used to assert the result. This gives a solid overview of the workflow.
Hands-On: Testing a POST Endpoint
Let's apply this to our blog platform. Assume we have the following PostController which depends on the PostService from the previous lesson. We'll also use a DTO (CreatePostRequest) to separate our API contract from our domain model.
CreatePostRequest.java (DTO)
// In a new 'dto' sub-package: src/main/java/.../posts/dto/CreatePostRequest.java
public class CreatePostRequest {
private String title;
private String content;
// Getters, Setters, Constructors
}
PostController.java
// In src/main/java/.../posts/PostController.java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping
public ResponseEntity<Post> createPost(@RequestBody CreatePostRequest request) {
Post createdPost = postService.createPost(request.getTitle(), request.getContent());
return new ResponseEntity<>(createdPost, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity<Post> getPostById(@PathVariable Long id) {
Post post = postService.findById(id); // Assume findById exists in PostService
return ResponseEntity.ok(post);
}
}
Now, let's write PostControllerTest.java. We'll test the createPost endpoint.
PostControllerTest.java
// In src/test/java/.../posts/PostControllerTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
// 1. Specify the controller to test and load the web layer context
@WebMvcTest(PostController.class)
class PostControllerTest {
// 2. Autowire MockMvc to perform requests
@Autowired
private MockMvc mockMvc;
// 3. Provide a mock implementation for the service dependency
@MockBean
private PostService postService;
// 4. Autowire ObjectMapper to convert Java objects to JSON
@Autowired
private ObjectMapper objectMapper;
@Test
void createPost_whenValidInput_shouldReturn201AndPost() throws Exception {
// --- Arrange ---
// Input DTO for the request body
CreatePostRequest requestDto = new CreatePostRequest("New Post", "Some content");
// The Post object that the mocked service will return
Post returnedPost = new Post();
returnedPost.setId(1L);
returnedPost.setTitle("New Post");
returnedPost.setContent("Some content");
// Stub the service method: when createPost is called with these details, return our Post object
when(postService.createPost("New Post", "Some content")).thenReturn(returnedPost);
// --- Act & Assert ---
mockMvc.perform(post("/api/posts") // Perform a POST request
.contentType(MediaType.APPLICATION_JSON) // Set the content type header
.content(objectMapper.writeValueAsString(requestDto))) // Set the request body as a JSON string
.andExpect(status().isCreated()) // Assert that the HTTP status is 201 Created
.andExpect(jsonPath("$.id").value(1L)) // Use JSONPath to assert fields in the response body
.andExpect(jsonPath("$.title").value("New Post"));
}
}
Let's break down the andExpect part, as this is new:
status().isCreated(): Checks if the HTTP response status is 201. You can also use.isOk()(200),.isBadRequest()(400), etc.jsonPath("$.id").value(1L): This is extremely powerful. It parses the JSON response and lets you assert values using JSONPath expressions. The$represents the root of the JSON object.
For a detailed look at testing an endpoint that accepts a JSON body, watch this next clip.
Spring Boot | Controller Unit Testing | Mockito | MockMVC
This segment from TheCodeStorm demonstrates exactly how to test a POST endpoint. It covers using ObjectMapper to create the JSON request body and jsonPath to verify the response.
Watch from 09:40 to 13:50. Pay close attention to how the input object is converted to a string for the .content() method and how jsonPath() is used to make assertions on specific fields in the returned JSON.
Your Task: Write a Test for a GET Endpoint
Now it's your turn. Using the PostControllerTest.java class we just created, add a new test method to verify the getPostById endpoint.
Your Goal: Write a test named getPostById_whenPostExists_shouldReturn200AndPost.
- Arrange:
- Define a post ID to test with (e.g.,
1L). - Create a
Postobject that the service will "find". - Stub the
postService.findById(1L)method to return your createdPostobject.
- Define a post ID to test with (e.g.,
- Act:
- Use
mockMvc.perform()to make aGETrequest to/api/posts/1.
- Use
- Assert:
- Expect the status to be
isOk()(200). - Expect the
idin the JSON response to be1L. - Expect the
titleto match the title of your stubbedPostobject.
- Expect the status to be
Here's a code block for you to fill in. I recommend trying to write it yourself first, but you can reference the comprehensive examples in the bezkoder.com article if you get stuck.
Spring Boot - Rest Controller Unit Test with @WebMvcTest - BezKoder
This article from Bezkoder provides a complete, copy-pasteable example of a controller test class with tests for all CRUD operations. It's an excellent reference for the syntax.
Look at the shouldReturnTutorial() test method in the code block. It shows exactly how to test a GET-by-ID endpoint, which is what you're about to do.
Fill in your test here:
// Inside PostControllerTest.java
@Test
void getPostById_whenPostExists_shouldReturn200AndPost() throws Exception {
// TODO: Arrange - create a Post and stub postService.findById()
// TODO: Act & Assert - perform a GET request and check status and jsonPath
}
Click here for the solution
@Test
void getPostById_whenPostExists_shouldReturn200AndPost() throws Exception {
// Arrange
Long postId = 1L;
Post foundPost = new Post();
foundPost.setId(postId);
foundPost.setTitle("Test Post");
foundPost.setContent("Test Content");
when(postService.findById(postId)).thenReturn(foundPost);
// Act & Assert
mockMvc.perform(get("/api/posts/{id}", postId)) // Use a path variable
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(postId))
.andExpect(jsonPath("$.title").value("Test Post"));
}
Debugging Task: The Unexpected 404
A common mistake in controller tests is a mismatch between what the test requests and what the MockMvc request is configured to do, or forgetting to stub a service method.
- In your
getPostById_whenPostExists_shouldReturn200AndPosttest, comment out thewhen(postService.findById(postId)).thenReturn(foundPost);line. - Run the test in debug mode and place a breakpoint inside the
getPostByIdmethod in yourPostController. - Your task:
- Step through the execution. What value is returned by
postService.findById(id)? - Because Mockito returns
nullfor non-stubbed methods returning objects, your controller receivesnull. What happens next? ANullPointerExceptionmight occur if you try to use thepostobject. Spring might also handle this and return a 404 or 500 depending on configuration. - Observe the final test failure. The assertion likely fails because it expected a 200 OK status but received something else. This runtime observation shows you the direct consequence of a missing stub in the web layer.
- Uncomment the line to fix the test.
- Step through the execution. What value is returned by
Conclusion
Excellent work! You have now learned how to test the web layer of your Spring Boot application in isolation, a critical skill for building robust and reliable APIs.
Key Takeaways:
@WebMvcTestcreates a focused test "slice" for the web layer, excluding services and repositories.@MockBeanis used to inject mock dependencies into the Spring application context for these tests.MockMvcis your tool for simulating HTTP requests (.perform()) and making assertions on the response (.andExpect()).- JSONPath (
jsonPath("$.field")) provides a powerful way to inspect and verify the content of your JSON responses. - This entire workflow is the Spring equivalent of using
supertestandJestto test your Express route handlers.
Preview of the Next Lesson:
So far, we've tested our service and controller layers with mocks. But what about the database interaction itself? In the next lesson, we'll dive into writing an integration test for the repository layer using @DataJpaTest. You'll learn how to test your JPA queries against a real (but in-memory) database, ensuring your data access layer works as expected.