Testing with MockMvc
MockMvc is a test tool that calls a Spring app without starting a server. A MockMvc test sends a fake request and checks the answer.
Start the app for the test
These two marks start the whole app and add MockMvc. The test class holds the test methods.
@SpringBootTest
@AutoConfigureMockMvc
class TaskControllerTest {
}Ask for the task list
This test sends a GET request to /tasks. The andExpect call checks that the status is 200.
mockMvc.perform(get("/tasks"))
.andExpect(status().isOk());Example
package com.example.demo;
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.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class TaskControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void getTasksReturnsOk() throws Exception {
mockMvc.perform(get("/tasks")).andExpect(status().isOk());
}
}Key points
- @SpringBootTest starts the whole app for the test.
- @AutoConfigureMockMvc adds MockMvc to the test.
- MockMvc sends requests without a running server.
- The perform call sends one request to the app.
- The andExpect call checks the answer that comes back.
In this example, @SpringBootTest starts the whole app for the test. @AutoConfigureMockMvc adds MockMvc to the test. The MockMvc field is filled in by Spring. The test method sends a GET request to /tasks. The andExpect call checks that the answer status is 200. The test run reports one test run with no failures.
Note
MockMvc tests need spring-boot-starter-webmvc-test in the build.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does MockMvc do in a test?