The previous part of my Spring MVC Test tutorial described how we can send HTTP requests to the system under test and write assertions for the response returned by the tested controller method. This blog post describes how we can use the information provided by the previous part of this tutorial when we are writing unit tests for a controller method which renders the information of a single item.
After we have finished this blog post, we:
- Know how we can ensure that the system under test returns the correct HTTP status code.
- Can verify that the system under test renders the correct view.
- Understand how we can ensure that our model attributes contain the correct information.
Let’s begin.
This blog post assumes that:
Introduction to the System Under Test
We have to write unit tests for a controller method which processes GET requests send to the path: ‘/todo-item/{id}’. This method returns the HTTP status code 200 and renders the information of a todo item whose id is given as the value of the id path variable. If the requested todo item isn’t found from the database, this method returns the HTTP status code 404 and renders the not found view.
The tested controller method is called findById() and it’s implemented by following these steps:
- Find the todo item from the database by invoking the
findById()method of theTodoItemCrudServiceclass. Pass the id of the todo item to the invoked method as an argument. - Put the found todo item to a model attribute called
todoItem. - Return the name of the view (’todo-item/view’) that renders the information of the found todo item.
The source code of the tested controller method looks as follows:
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.stereotype.Controller;
3import org.springframework.ui.Model;
4import org.springframework.web.bind.annotation.GetMapping;
5import org.springframework.web.bind.annotation.PathVariable;
6import org.springframework.web.bind.annotation.RequestMapping;
7
8import java.util.List;
9
10@Controller
11@RequestMapping("/todo-item")
12public class TodoItemCrudController {
13
14 private final TodoItemCrudService service;
15
16 @Autowired
17 public TodoItemCrudController(TodoItemCrudService service) {
18 this.service = service;
19 }
20
21 @GetMapping("{id}")
22 public String findById(@PathVariable("id") Long id, Model model) {
23 TodoItemDTO found = service.findById(id);
24 model.addAttribute("todoItem", found);
25 return "todo-item/view";
26 }
27}
The TodoItemDTO class is a DTO that contains the information of a single todo item. Its source code looks as follows:
1public class TodoItemDTO {
2
3 private Long id;
4 private String description;
5 private List<TagDTO> tags;
6 private String title;
7 private TodoItemStatus status;
8
9 //Getters and setters are omitted
10}
The TagDTO class is a DTO that contains the information of a single tag. Its source code looks as follows:
1public class TagDTO {
2
3 private Long id;
4 private String name;
5
6 //Getters and setters are omitted
7}
The TodoItemStatus enum specifies the possible statuses of a todo item. Its source code looks as follows:
1public enum TodoItemStatus {
2 OPEN,
3 IN_PROGRESS,
4 DONE
5}
Next, we will learn how we can write assertions for the response returned by the system under test.
Writing Assertions for the Response Returned by the System Under Test
Before we can write unit tests for a Spring MVC controller which renders data, we have to learn how we can write assertions for the response returned by the system under test. When we want to write assertions for the response returned by the tested Spring MVC controller, we have to use these static methods of the MockMvcResultMatchers class:
- The
status()method returns aStatusResultMatchersobject which allows us to write assertions for the returned HTTP status. - The
view()method returns aViewResultMatchersobject which allows us to write assertions for the rendered view. - The
model()method returns aModelResultMatchersobject which allows us to write assertions for the Spring MVC model.
Additional Reading:
Let’s move on and find out how we can write a request builder method which sends GET requests to the system under test.
Writing a New Request Builder Method
Because we want to remove duplicate code from our test class, we have to create and send HTTP requests to the system under test by using a so called request builder class. In other words, before we can write unit tests for the system under test, we have write to a request builder method which creates and sends HTTP requests to the system under test. We can write this request builder method by following these steps:
- Add a new method called
findById()to our request builder class. Ensure that this method takes the id of the todo item as a method parameter and returns aResultActionsobject. - Send a
GETrequest to the path: ‘/todo-item/{id}’ by invoking theperform()method of theMockMvcclass. Remember to return theResultActionsobject that’s returned by theperform()method.
After we have written our request builder method, the source code of our request builder class looks as follows:
1import org.springframework.test.web.servlet.MockMvc;
2import org.springframework.test.web.servlet.ResultActions;
3
4import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
5
6class TodoItemRequestBuilder {
7
8 private final MockMvc mockMvc;
9
10 TodoItemRequestBuilder(MockMvc mockMvc) {
11 this.mockMvc = mockMvc;
12 }
13
14 ResultActions findById(Long id) throws Exception {
15 return mockMvc.perform(get("/todo-item/{id}", id));
16 }
17}
Additional Reading:
Next, we will learn to write unit tests for the system under test.
Writing Unit Tests for the System Under Test
When we want to write unit tests for the system under test, we have to follow these steps:
First, we have to add the required class hierarchy to our test class. Because we are writing unit tests, we can create this class hierarchy by following these steps:
- Add an inner class called
FindByIdto our test class. This inner class contains the test methods which ensure that the system under test is working as expected. - Add an inner class called
WhenRequestedTodoItemIsNotFoundto theFindByIdclass. This inner class contains the test methods which ensure that the system under test is working as expected when the requested todo item isn’t found from the database. - Add an inner class called
WhenRequestedTodoItemIsFoundto theFindByIdclass. This inner class contains the test methods which ensure that the system under test is working as expected when the requested todo item is found from the database.
After we have created the required class hierarchy, the source code of our test class looks as follows:
1import org.junit.jupiter.api.BeforeEach;
2import org.junit.jupiter.api.DisplayName;
3import org.junit.jupiter.api.Nested;
4import org.springframework.test.web.servlet.MockMvc;
5import org.springframework.test.web.servlet.setup.MockMvcBuilders;
6
7import static net.petrikainulainen.springmvctest.junit5.web.WebTestConfig.*;
8import static org.mockito.Mockito.mock;
9
10class TodoItemCrudControllerTest {
11
12 private TodoItemRequestBuilder requestBuilder;
13 private TodoItemCrudService service;
14
15 @BeforeEach
16 void configureSystemUnderTest() {
17 service = mock(TodoItemCrudService.class);
18
19 MockMvc mockMvc = MockMvcBuilders
20 .standaloneSetup(new TodoItemCrudController(service))
21 .setHandlerExceptionResolvers(exceptionResolver())
22 .setLocaleResolver(fixedLocaleResolver())
23 .setViewResolvers(jspViewResolver())
24 .build();
25 requestBuilder = new TodoItemRequestBuilder(mockMvc);
26 }
27
28 @Nested
29 @DisplayName("Render the the information of the requested todo item")
30 class FindById {
31
32 @Nested
33 @DisplayName("When the requested todo item isn't found from the database")
34 class WhenRequestedTodoItemIsNotFound {
35
36 }
37
38 @Nested
39 @DisplayName("When the requested todo item is found from the database")
40 class WhenRequestedTodoItemIsFound {
41
42 }
43 }
44}
Second, we have to ensure that the system under test is working as expected when the requested todo item isn’t found from the database. We can write the required test methods by following these steps:
- Add a constant called
TODO_ITEM_IDto theFindByIdclass. This constant specifies the id of the requested todo item. We have to add this constant to theFindByIdclass because its value is used by test methods found from theWhenRequestedTodoItemIsNotFoundandWhenRequestedTodoItemIsFoundclasses. - Add a new setup method to the
WhenRequestedTodoItemIsNotFoundclass and ensure that it’s run before a test method is run. When we implement this setup method, we must ensure that theTodoItemCrudServiceobject throws aTodoItemNotFoundExceptionwhen itsfindById()method is invoked by using the argument:99L. - Ensure that the system under test returns the HTTP status code 404.
- Verify that the system under test renders the not found view.
After we have written the required test methods, the source code of our test class looks as follows:
1import org.junit.jupiter.api.BeforeEach;
2import org.junit.jupiter.api.DisplayName;
3import org.junit.jupiter.api.Nested;
4import org.junit.jupiter.api.Test;
5import org.springframework.test.web.servlet.MockMvc;
6import org.springframework.test.web.servlet.setup.MockMvcBuilders;
7
8import static net.petrikainulainen.springmvctest.junit5.web.WebTestConfig.*;
9import static org.mockito.BDDMockito.given;
10import static org.mockito.Mockito.mock;
11import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
12import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
13
14class TodoItemCrudControllerTest {
15
16 private TodoItemRequestBuilder requestBuilder;
17 private TodoItemCrudService service;
18
19 @BeforeEach
20 void configureSystemUnderTest() {
21 service = mock(TodoItemCrudService.class);
22
23 MockMvc mockMvc = MockMvcBuilders
24 .standaloneSetup(new TodoItemCrudController(service))
25 .setHandlerExceptionResolvers(exceptionResolver())
26 .setLocaleResolver(fixedLocaleResolver())
27 .setViewResolvers(jspViewResolver())
28 .build();
29 requestBuilder = new TodoItemRequestBuilder(mockMvc);
30 }
31
32 @Nested
33 @DisplayName("Render the information of the requested todo item")
34 class FindById {
35
36 private final Long TODO_ITEM_ID = 99L;
37
38 @Nested
39 @DisplayName("When the requested todo item isn't found from the database")
40 class WhenRequestedTodoItemIsNotFound {
41
42 @BeforeEach
43 void serviceThrowsNotFoundException() {
44 given(service.findById(TODO_ITEM_ID))
45 .willThrow(new TodoItemNotFoundException(""));
46 }
47
48 @Test
49 @DisplayName("Should return the HTTP status code 404")
50 void shouldReturnHttpStatusCodeNotFound() throws Exception {
51 requestBuilder.findById(TODO_ITEM_ID)
52 .andExpect(status().isNotFound());
53 }
54
55 @Test
56 @DisplayName("Should render the 404 view")
57 void shouldRender404View() throws Exception {
58 requestBuilder.findById(TODO_ITEM_ID)
59 .andExpect(view().name("error/404"));
60 }
61 }
62
63 //The other inner class is omitted
64 }
65}
Third, we have to ensure that the system under test is working as expected when the requested todo item is found from the database. We can write the required test methods by following these steps:
- Add the required constants to the
WhenRequestedTodoItemIsFoundclass. These constants specify the property values of the found todo item. - Add a new setup method to the
WhenRequestedTodoItemIsFoundclass and ensure that it’s run before a test method is run. When we implement this setup method, we must ensure that theTodoItemCrudServiceobject returns the information of the found todo item when itsfindById()method is invoked by using the argument:99L. - Ensure that the system under test returns the HTTP status code 200.
- Verify that the system under test renders the view which displays the information of the found todo item.
- Ensure that the system under test displays the information of the correct todo item.
- Verify that the system under test displays the correct title and description.
- Ensure that the system under test displays an open todo item.
- Verify that the system under test displays a todo item that has one tag.
- Ensure that the system under test displays the information of the found tag.
After we have written the required test methods, the source code of our test class looks as follows:
1import org.junit.jupiter.api.BeforeEach;
2import org.junit.jupiter.api.DisplayName;
3import org.junit.jupiter.api.Nested;
4import org.junit.jupiter.api.Test;
5import org.springframework.test.web.servlet.MockMvc;
6import org.springframework.test.web.servlet.setup.MockMvcBuilders;
7
8import java.util.Collections;
9
10import static net.petrikainulainen.springmvctest.junit5.web.WebTestConfig.*;
11import static org.hamcrest.Matchers.allOf;
12import static org.hamcrest.Matchers.equalTo;
13import static org.hamcrest.Matchers.hasItem;
14import static org.hamcrest.Matchers.hasProperty;
15import static org.hamcrest.Matchers.hasSize;
16import static org.mockito.BDDMockito.given;
17import static org.mockito.Mockito.mock;
18import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
19import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
20import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
21
22class TodoItemCrudControllerTest {
23
24 private TodoItemRequestBuilder requestBuilder;
25 private TodoItemCrudService service;
26
27 @BeforeEach
28 void configureSystemUnderTest() {
29 service = mock(TodoItemCrudService.class);
30
31 MockMvc mockMvc = MockMvcBuilders
32 .standaloneSetup(new TodoItemCrudController(service))
33 .setHandlerExceptionResolvers(exceptionResolver())
34 .setLocaleResolver(fixedLocaleResolver())
35 .setViewResolvers(jspViewResolver())
36 .build();
37 requestBuilder = new TodoItemRequestBuilder(mockMvc);
38 }
39
40 @Nested
41 @DisplayName("Render the information of the requested todo item")
42 class FindById {
43
44 private final Long TODO_ITEM_ID = 99L;
45
46 //The other inner class is omitted
47
48 @Nested
49 @DisplayName("When the requested todo item is found from the database")
50 class WhenRequestedTodoItemIsFound {
51
52 private final String TITLE = "Write example project";
53 private final String DESCRIPTION = "Use JUnit 5";
54 private final TodoItemStatus STATUS_OPEN = TodoItemStatus.OPEN;
55
56 private final Long TAG_ID = 44L;
57 private final String TAG_NAME = "tag";
58
59 @BeforeEach
60 void serviceReturnsOpenTodoItemWithOneTag() {
61 TodoItemDTO found = new TodoItemDTO();
62 found.setId(TODO_ITEM_ID);
63 found.setTitle(TITLE);
64 found.setDescription(DESCRIPTION);
65 found.setStatus(STATUS_OPEN);
66
67 TagDTO tag = new TagDTO();
68 tag.setId(TAG_ID);
69 tag.setName(TAG_NAME);
70 found.setTags(Collections.singletonList(tag));
71
72 given(service.findById(TODO_ITEM_ID)).willReturn(found);
73 }
74
75 @Test
76 @DisplayName("Should return the HTTP status code 200")
77 void shouldReturnHttpStatusCodeOk() throws Exception {
78 requestBuilder.findById(TODO_ITEM_ID)
79 .andExpect(status().isOk());
80 }
81
82 @Test
83 @DisplayName("Should render the view todo item view")
84 void shouldRenderViewTodoItemView() throws Exception {
85 requestBuilder.findById(TODO_ITEM_ID)
86 .andExpect(view().name("todo-item/view"));
87 }
88
89 @Test
90 @DisplayName("Should display the information of the correct todo item")
91 void shouldDisplayInformationOfCorrectTodoItem() throws Exception {
92 requestBuilder.findById(TODO_ITEM_ID)
93 .andExpect(model().attribute(
94 "todoItem",
95 hasProperty("id", equalTo(TODO_ITEM_ID))
96 ));
97 }
98
99 @Test
100 @DisplayName("Should display the correct title and description")
101 void shouldDisplayCorrectTitleAndDescription() throws Exception {
102 requestBuilder.findById(TODO_ITEM_ID)
103 .andExpect(model().attribute(
104 "todoItem",
105 allOf(
106 hasProperty("title", equalTo(TITLE)),
107 hasProperty("description",equalTo(DESCRIPTION))
108 )
109 ));
110 }
111
112 @Test
113 @DisplayName("Should display an open todo item")
114 void shouldDisplayOpenTodoItem() throws Exception {
115 requestBuilder.findById(TODO_ITEM_ID)
116 .andExpect(model().attribute(
117 "todoItem",
118 hasProperty("status", equalTo(STATUS_OPEN))
119 ));
120 }
121
122 @Test
123 @DisplayName("Should display a todo item that has one tag")
124 void shouldDisplayTodoItemThatHasOneTag() throws Exception {
125 requestBuilder.findById(TODO_ITEM_ID)
126 .andExpect(model().attribute(
127 "todoItem",
128 hasProperty("tags", hasSize(1))
129 ));
130 }
131
132 @Test
133 @DisplayName("Should display the information of the found tag")
134 void shouldDisplayInformationOfFoundTag() throws Exception {
135 requestBuilder.findById(TODO_ITEM_ID)
136 .andExpect(model().attribute(
137 "todoItem",
138 hasProperty("tags", hasItem(
139 allOf(
140 hasProperty("id", equalTo(TAG_ID)),
141 hasProperty("name", equalTo(TAG_NAME))
142 )
143 ))
144 ));
145 }
146 }
147 }
148}
Additional Reading:
- The Javadoc of the
MockMvcResultMatchersclass - The Javadoc of the
ModelResultMatchersclass - [The Javadoc of the
StatusResultMatchersclass - The Javadoc of the
ViewResultMatchersclass](https://docs.spring.io/spring-framework/docs/5.3.x/javadoc-api/org/springframework/test/web/servlet/result/StatusResultMatchers.html) - The Javadoc of the
Matchersclass
We can now write unit tests for a controller method that renders the information of a single item. Let’s summarize what we learned from this blog post.
Summary
This blog post has taught us four things:
- When we want to write assertions for the returned HTTP status, we have to invoke the
status()method of theMockMvcResultMatchersclass. - When we want to write assertions for the rendered view, we have to invoke the
view()method of theMockMvcResultMatchersclass. - When we want to write assertions for the Spring MVC model, we have to invoke the
model()method of theMockMvcResultMatchersclass. - We can use Hamcrest matchers for writing assertions for the model attributes found from the Spring MVC model.
P.S. You can get the example application of this blog post from Github.