Introduction to Mock Testing with Spring MVC and MockMvc
This article introduces mock testing for Spring MVC controllers, explains why mocks are useful, describes the main MockMvc components, shows required Maven dependencies, and provides complete example test cases for both view‑returning and JSON‑returning endpoints using JUnit and MockMvc.
In the previous chapters we covered JUnit and spring-test; this section focuses on mock testing for Spring MVC controllers, providing a beginner‑level guide that demonstrates testing methods returning views and JSON data.
What is mock testing? It uses virtual objects (mocks) to replace hard‑to‑construct or external dependencies during tests, reducing coupling and keeping tests lightweight, simple, and flexible.
Why use mock testing? It avoids tight coupling between modules and makes tests easier to write and maintain.
MockMvc Overview – MockMvc allows full Spring MVC request processing from URL to controller handling and view rendering. Key components include:
MockMvcBuilder (StandaloneMockMvcBuilder, DefaultMockMvcBuilder) – created via the static factory MockMvcBuilders .
MockMvc – the entry point for server‑side MVC tests.
ResultActions – provides andExpect , andDo , and andReturn methods.
MockMvcRequestBuilders – builds request objects (e.g., MockHttpServletRequestBuilder , MockMultipartHttpServletRequestBuilder ).
MockMvcResultMatchers – validates results and throws exceptions on mismatches.
MockMvcResultHandlers – processes results, such as print() to output the response.
MvcResult – contains the test execution result for custom verification.
Dependencies
<!-- spring test component -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- json‑path for JSON assertions -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>Test Class: ItemMockTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/*.xml")
@WebAppConfiguration
public class ItemMockTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void init() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
}Two controller methods are tested: one returning a view ( editItem ) and another returning JSON ( getItem ).
View‑returning test
@Test
public void test() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/editItem").param("id", "1"))
.andExpect(MockMvcResultMatchers.view().name("itemEdit"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
Assert.assertNotNull(result.getModelAndView().getModel().get("item"));
}JSON‑returning test
@Test
public void test1() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/getItem")
.param("id", "1")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value("IPhone X"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}These tests demonstrate how to set up MockMvc, perform requests, verify view names, HTTP status, content type, and JSON fields, and print the results for debugging.
Conclusion – Only a small portion of MockMvc is covered here; deeper study will help develop good unit‑testing habits for Spring controllers, ensuring reliability and maintainability of backend services.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.