middle
Как выполнять запросы и проверять результаты в MockMvc?
MockMvc предоставляет DSL для выполнения HTTP-запросов и проверки ответов без запуска реального сервера.
Выполнение запросов (perform)
Примеры запросов
// GET-запрос с параметрами
mockMvc.perform(get("/api/users")
.param("page", "0")
.param("size", "10")
.header("Authorization", "Bearer token123")
.accept(MediaType.APPLICATION_JSON));
// POST-запрос с JSON-телом
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(userDto)));
// PUT-запрос
mockMvc.perform(put("/api/users/{id}", 1)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"Обновлённый\"}"));
// DELETE-запрос
mockMvc.perform(delete("/api/users/{id}", 1));
// Multipart (загрузка файлов)
mockMvc.perform(multipart("/api/upload")
.file(new MockMultipartFile("file", "test.txt",
"text/plain", "содержимое".getBytes())));
Проверка результатов (andExpect)
Пример
mockMvc.perform(get("/api/users/1"))
// Статус ответа
.andExpect(status().isOk()) // 200
.andExpect(status().isCreated()) // 201
.andExpect(status().isBadRequest()) // 400
.andExpect(status().isNotFound()) // 404
// Заголовки
.andExpect(header().string("Content-Type", "application/json"))
.andExpect(header().exists("X-Custom-Header"))
// Содержимое ответа
.andExpect(content().string("hello"))
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
Работа с JSON через jsonPath
Пример
mockMvc.perform(get("/api/users"))
.andExpect(jsonPath("$[0].name").value("Иван"))
.andExpect(jsonPath("$", hasSize(3)))
.andExpect(jsonPath("$[0].email").exists())
.andExpect(jsonPath("$[0].password").doesNotExist())
.andExpect(jsonPath("$[0].id").isNumber())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$[0].name", containsString("Ив")))
.andExpect(jsonPath("$[0].age", greaterThan(18)));
Получение и обработка результата
Пример
MvcResult result = mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andDo(print()) // выводит детали запроса/ответа в консоль
.andReturn();
String json = result.getResponse().getContentAsString();
List<UserDto> users = objectMapper.readValue(json,
new TypeReference<List<UserDto>>() {});
assertEquals(2, users.size());
На собеседовании: покажите, что знаете три основных метода:
perform(выполнение),andExpect(проверка),andReturn(получение результата). Частая ошибка — забыть проjsonPathи пытаться десериализовать ответ вручную для каждой проверки.