/
NikolayVasiljev
/
java-reboot
Обзор
Документация
Войти
/
NikolayVasiljev
/
java-reboot
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
lesson11/src/test/java/com/example/module11/UserControllerTest.java
88 строк
3 KB
Николай
lesson11
06 июл 2025, 21:17
06 июл 2025, 21:17
aab6008
Код
Авторство
О чём код?
package com.example.module11; import com.example.module11.entity.User; import com.example.module11.entity.UserController; import com.example.module11.entity.UserService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; 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.test.web.servlet.MockMvc; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.util.Arrays; import java.util.Optional; @WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void testListUsers() throws Exception { User user1 = new User("Alice", 35); User user2 = new User("Bob", 29); when(userService.getAllUsers()).thenReturn(Arrays.asList(user1, user2)); mockMvc.perform(get("/users")) .andExpect(status().isOk()) .andExpect(view().name("users")) .andExpect(model().attributeExists("users")); } @Test public void testAddUser() throws Exception { User user=new User("Nikolay",51); // Выполняем POST-запрос с параметрами формы mockMvc.perform(post("/users/add") .param("name", "Nikolay") .param("age", "51")) .andExpect(status().is3xxRedirection()) // Проверка, что редирект .andExpect(redirectedUrl("/users")); // Проверка URL редиректа // Проверяем, что вызван метод saveUser с правильным объектом Mockito.verify(userService).saveUser(user); } @Test public void testDeleteUser() throws Exception { Long userId = 5L; // Выполняем GET-запрос на удаление пользователя по id mockMvc.perform(get("/users/delete/{id}", userId)) .andExpect(status().is3xxRedirection()) // ожидаем редирект .andExpect(redirectedUrl("/users")); // редирект на список // Проверяем, что вызван метод deleteUser с правильным id Mockito.verify(userService).deleteUser(userId); } @Test public void testShowEditForm_UserFound() throws Exception { User user=new User(); user.setId(1L); user.setName("Nikolay"); user.setAge(51); when(userService.getUserById(1l)).thenReturn(Optional.of(user)); mockMvc.perform(get("/users/edit/1")) .andExpect(status().isOk()) .andExpect(view().name("edit-user")) .andExpect(model().attributeExists("user")) .andExpect(model().attribute("user", user));} @Test public void testShowEditForm_UserNotFound() throws Exception { when(userService.getUserById(999L)).thenReturn(Optional.empty()); mockMvc.perform(get("/users/edit/999")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/users"));} }