diff --git a/src/main/java/ru/job4j/cars/controller/UserController.java b/src/main/java/ru/job4j/cars/controller/UserController.java index fa20ab9..d8f3a18 100644 --- a/src/main/java/ru/job4j/cars/controller/UserController.java +++ b/src/main/java/ru/job4j/cars/controller/UserController.java @@ -79,6 +79,7 @@ public String updateUser(@ModelAttribute User user, Model model, HttpSession ses boolean updated = userService.update(user); if (!updated) { model.addAttribute("error", "Ошибка при обновлении данных пользователя."); + model.addAttribute("user", session.getAttribute("user")); return "users/update"; } session.invalidate(); @@ -90,6 +91,7 @@ public String deleteUser(@RequestParam String password, Model model, HttpSession User actualUser = (User) session.getAttribute("user"); if (!password.equals(actualUser.getPassword())) { model.addAttribute("error", "Введенный пароль не совпадает с паролем пользователя."); + model.addAttribute("user", session.getAttribute("user")); return "users/update"; } session.invalidate(); diff --git a/src/test/java/cars/controller/ImageControllerTest.java b/src/test/java/cars/controller/ImageControllerTest.java new file mode 100644 index 0000000..5da5177 --- /dev/null +++ b/src/test/java/cars/controller/ImageControllerTest.java @@ -0,0 +1,53 @@ +package cars.controller; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import ru.job4j.cars.Main; +import ru.job4j.cars.dto.ImageDto; +import ru.job4j.cars.service.ImageService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(classes = Main.class) +@AutoConfigureMockMvc +class ImageControllerTest { + + @Autowired + private MockMvc mockMvc; + @MockBean + private ImageService imageService; + + @Test + void whenGetRequestImageIdThenResponseOkWithByteArray() throws Exception { + ImageDto imageDto = new ImageDto("name", new byte[1]); + + when(imageService.getImageDtoById(any(Integer.class))).thenReturn(imageDto); + + MvcResult mvcResult = mockMvc.perform(get("/images/1")) + .andExpect(status().isOk()) + .andReturn(); + assertThat(mvcResult.getResponse().getContentAsByteArray()).isEqualTo(new byte[1]); + } + + @Test + void whenGetRequestDefaultImageThenResponseOkWithByteArray() throws Exception { + ImageDto imageDto = new ImageDto("name", new byte[1]); + + when(imageService.getDefaultImageDto()).thenReturn(imageDto); + + MvcResult mvcResult = mockMvc.perform(get("/images/defaultImage")) + .andExpect(status().isOk()) + .andReturn(); + assertThat(mvcResult.getResponse().getContentAsByteArray()).isEqualTo(new byte[1]); + } + +} \ No newline at end of file diff --git a/src/test/java/cars/controller/IndexControllerTest.java b/src/test/java/cars/controller/IndexControllerTest.java index 8346d85..6e4951a 100644 --- a/src/test/java/cars/controller/IndexControllerTest.java +++ b/src/test/java/cars/controller/IndexControllerTest.java @@ -20,7 +20,7 @@ class IndexControllerTest { private MockMvc mockMvc; @Test - void whenGetRequestIndexThenReturnAllPostsPage() throws Exception { + void whenGetRequestIndexThenRedirectAllPostsPage() throws Exception { this.mockMvc.perform(get("/index")) .andDo(print()) .andExpect(status().is3xxRedirection()) diff --git a/src/test/java/cars/controller/PostControllerTest.java b/src/test/java/cars/controller/PostControllerTest.java new file mode 100644 index 0000000..b56aff9 --- /dev/null +++ b/src/test/java/cars/controller/PostControllerTest.java @@ -0,0 +1,268 @@ +package cars.controller; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import cars.util.ControllerTestUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import ru.job4j.cars.Main; +import ru.job4j.cars.dto.ImageDto; +import ru.job4j.cars.dto.PostSearchDto; +import ru.job4j.cars.model.Post; +import ru.job4j.cars.service.*; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +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.multipart; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest(classes = Main.class) +@AutoConfigureMockMvc +class PostControllerTest { + + private final ControllerTestUtil testUtil = new ControllerTestUtil(); + @Autowired + private MockMvc mockMvc; + @MockBean + private PostService postService; + @MockBean + private BodyService bodyService; + @MockBean + private BrandService brandService; + @MockBean + private CarModelService carModelService; + @MockBean + private CategoryService categoryService; + @MockBean + private ColorService colorService; + @MockBean + private EngineSizeService engineSizeService; + @MockBean + private FuelTypeService fuelTypeService; + @MockBean + private TransmissionService transmissionService; + private MockHttpSession mockHttpSession; + private MockMultipartFile testFile; + + @BeforeEach + void init() { + mockHttpSession = new MockHttpSession(); + testFile = new MockMultipartFile("file", "file", MediaType.IMAGE_JPEG_VALUE, new byte[] {1}); + } + + @Test + void whenGetRequestPostsAllThenGetAllNotSoldPostsPage() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + + mockCarAttributesGathering(post); + when(postService.findAllNotSold()).thenReturn(List.of(post)); + + this.mockMvc.perform(get("/posts/all")) + .andDo(print()) + .andExpect(model().attributeExists("brandsModels")) + .andExpect(model().attributeExists("bodies")) + .andExpect(model().attributeExists("transmissions")) + .andExpect(model().attributeExists("fuelTypes")) + .andExpect(model().attributeExists("engineSizes")) + .andExpect(model().attributeExists("colors")) + .andExpect(model().attributeExists("categories")) + .andExpect(model().attributeExists("posts")) + .andExpect(model().attribute("posts", List.of(post))) + .andExpect(status().isOk()) + .andExpect(view().name("posts/list")); + verify(postService).findAllNotSold(); + } + + @Test + void whenGetRequestPostsAllWithSearchDtoThenGetPostsByCriteriaPage() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + + ArgumentCaptor searchCaptor = ArgumentCaptor.forClass(PostSearchDto.class); + mockCarAttributesGathering(post); + when(postService.findAllByCriteria(any(PostSearchDto.class))).thenReturn(List.of(post)); + + this.mockMvc.perform(get("/posts/all").param("imageExists", "true")) + .andDo(print()) + .andExpect(model().attributeExists("posts")) + .andExpect(model().attribute("posts", List.of(post))) + .andExpect(status().isOk()) + .andExpect(view().name("posts/list")); + verify(postService).findAllByCriteria(searchCaptor.capture()); + assertThat(searchCaptor.getValue().isImageExists()).isTrue(); + assertThat(searchCaptor.getValue().getCar()).isNull(); + } + + @Test + @WithMockUser + void whenGetRequestPostsCreateThenGetCreatePage() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + + mockHttpSession.setAttribute("user", testUtil.makeUser()); + mockCarAttributesGathering(post); + + this.mockMvc.perform(get("/posts/create").session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attributeExists("brandsModels")) + .andExpect(model().attributeExists("bodies")) + .andExpect(model().attributeExists("transmissions")) + .andExpect(model().attributeExists("fuelTypes")) + .andExpect(model().attributeExists("engineSizes")) + .andExpect(model().attributeExists("colors")) + .andExpect(model().attributeExists("categories")) + .andExpect(status().isOk()) + .andExpect(view().name("posts/create")); + } + + @Test + void whenGetRequestPostsIdThenGetPostPage() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + + when(postService.findById(any(Integer.class))).thenReturn(Optional.of(post)); + + this.mockMvc.perform(get("/posts/1")) + .andDo(print()) + .andExpect(model().attributeExists("post")) + .andExpect(model().attribute("post", post)) + .andExpect(status().isOk()) + .andExpect(view().name("posts/one")); + } + + @Test + void whenGetRequestPostsWrongIdThenGetErrorPage() throws Exception { + when(postService.findById(any(Integer.class))).thenReturn(Optional.empty()); + + this.mockMvc.perform(get("/posts/1")) + .andDo(print()) + .andExpect(model().attributeExists("message")) + .andExpect(model().attribute("message", "Объявление не найдено.")) + .andExpect(status().isOk()) + .andExpect(view().name("errors/404")); + } + + @Test + void whenGetRequestPostsEditIdThenGetPostEditPage() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + + when(postService.findById(any(Integer.class))).thenReturn(Optional.of(post)); + mockCarAttributesGathering(post); + + this.mockMvc.perform(get("/posts/edit/1")) + .andDo(print()) + .andExpect(model().attributeExists("post")) + .andExpect(model().attribute("post", post)) + .andExpect(status().isOk()) + .andExpect(view().name("posts/edit")); + } + + @Test + void whenGetRequestPostsEditWrongIdThenGetErrorPage() throws Exception { + when(postService.findById(any(Integer.class))).thenReturn(Optional.empty()); + + this.mockMvc.perform(get("/posts/edit/1")) + .andDo(print()) + .andExpect(model().attributeExists("message")) + .andExpect(model().attribute("message", "Объявление не найдено.")) + .andExpect(status().isOk()) + .andExpect(view().name("errors/404")); + } + + @Test + void whenPostRequestPostsCreateThenSavePostAndRedirectAllPostsPage() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.setAll(Map.of("description", "description", "price", "100")); + + ArgumentCaptor postCaptor = ArgumentCaptor.forClass(Post.class); + ArgumentCaptor imageCaptor = ArgumentCaptor.forClass(ImageDto.class); + mockHttpSession.setAttribute("user", testUtil.makeUser()); + when(postService.save(any(), any())).thenReturn(Optional.of(new Post())); + + this.mockMvc.perform(multipart("/posts/create") + .file(testFile) + .params(params) + .session(mockHttpSession)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/posts/all")); + verify(postService).save(postCaptor.capture(), imageCaptor.capture()); + assertThat(postCaptor.getValue().getDescription()).isEqualTo("description"); + assertThat(postCaptor.getValue().getPrice()).isEqualTo(100L); + assertThat(imageCaptor.getValue().getName()).isEqualTo("file"); + assertThat(imageCaptor.getValue().getContent()).isEqualTo(new byte[] {1}); + } + + @Test + void whenPostRequestPostsCreateWithWrongParamsThenGetErrorPage() throws Exception { + mockHttpSession.setAttribute("user", testUtil.makeUser()); + when(postService.save(any(), any())).thenReturn(Optional.empty()); + + this.mockMvc.perform(multipart("/posts/create").file(testFile).session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attributeExists("message")) + .andExpect(model().attribute("message", "Произошла ошибка при создании объявления.")) + .andExpect(status().isOk()) + .andExpect(view().name("errors/404")); + } + + @Test + void whenPostRequestPostsEditThenUpdatePostAndRedirectUsersPostsPage() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.setAll(Map.of("description", "description", "price", "100")); + + ArgumentCaptor postCaptor = ArgumentCaptor.forClass(Post.class); + ArgumentCaptor imageCaptor = ArgumentCaptor.forClass(ImageDto.class); + when(postService.update(any(), any())).thenReturn(true); + + this.mockMvc.perform(multipart("/posts/edit") + .file(testFile) + .params(params)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/users/posts")); + verify(postService).update(postCaptor.capture(), imageCaptor.capture()); + assertThat(postCaptor.getValue().getDescription()).isEqualTo("description"); + assertThat(postCaptor.getValue().getPrice()).isEqualTo(100L); + assertThat(imageCaptor.getValue().getName()).isEqualTo("file"); + assertThat(imageCaptor.getValue().getContent()).isEqualTo(new byte[] {1}); + } + + @Test + void whenPostRequestPostsEditWithWrongParamsThenGetErrorPage() throws Exception { + when(postService.update(any(), any())).thenReturn(false); + + this.mockMvc.perform(multipart("/posts/edit").file(testFile)) + .andDo(print()) + .andExpect(model().attributeExists("message")) + .andExpect(model().attribute("message", "Произошла ошибка при обновлении объявления.")) + .andExpect(status().isOk()) + .andExpect(view().name("errors/404")); + } + + private void mockCarAttributesGathering(Post post) { + when(carModelService.findAll()).thenReturn(List.of(post.getCar().getCarModel())); + when(brandService.findAll()).thenReturn(List.of(post.getCar().getBrand())); + when(bodyService.findAll()).thenReturn(List.of(post.getCar().getBody())); + when(transmissionService.findAll()).thenReturn(List.of(post.getCar().getTransmission())); + when(fuelTypeService.findAll()).thenReturn(List.of(post.getCar().getEngine().getFuelType())); + when(engineSizeService.findAll()).thenReturn(List.of(post.getCar().getEngine().getEngineSize())); + when(colorService.findAll()).thenReturn(List.of(post.getCar().getColor())); + when(categoryService.findAll()).thenReturn(List.of(post.getCar().getCategory())); + } + +} \ No newline at end of file diff --git a/src/test/java/cars/controller/UserControllerTest.java b/src/test/java/cars/controller/UserControllerTest.java new file mode 100644 index 0000000..a4e7de6 --- /dev/null +++ b/src/test/java/cars/controller/UserControllerTest.java @@ -0,0 +1,235 @@ +package cars.controller; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import cars.util.ControllerTestUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import ru.job4j.cars.Main; +import ru.job4j.cars.model.Post; +import ru.job4j.cars.model.User; +import ru.job4j.cars.service.PostService; +import ru.job4j.cars.service.UserService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +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.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest(classes = Main.class) +@AutoConfigureMockMvc +class UserControllerTest { + + private final ControllerTestUtil testUtil = new ControllerTestUtil(); + @Autowired + private MockMvc mockMvc; + @MockBean + private UserService userService; + @MockBean + private PostService postService; + private MockHttpSession mockHttpSession; + + @BeforeEach + void init() { + mockHttpSession = new MockHttpSession(); + } + + @Test + void whenGetRequestUsersRegisterThenReturnRegisterPage() throws Exception { + this.mockMvc.perform(get("/users/register")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(view().name("users/register")); + } + + @Test + void whenGetRequestUsersLoginThenReturnLoginPage() throws Exception { + this.mockMvc.perform(get("/users/login")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(view().name("users/login")); + } + + @Test + void whenGetRequestLogoutThenRedirectIndexPage() throws Exception { + assertThat(mockHttpSession.isInvalid()).isFalse(); + this.mockMvc.perform(get("/users/logout").session(mockHttpSession)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/")); + assertThat(mockHttpSession.isInvalid()).isTrue(); + } + + @Test + void whenGetRequestUsersUpdateThenReturnUpdatePage() throws Exception { + mockHttpSession.setAttribute("user", new User()); + + this.mockMvc.perform(get("/users/update").session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attributeExists("user")) + .andExpect(model().attribute("user", new User())) + .andExpect(status().isOk()) + .andExpect(view().name("users/update")); + } + + @Test + void whenGetRequestUsersPostsThenReturnPostsPageWithPosts() throws Exception { + Post post = testUtil.makePost(testUtil.makeUser(), testUtil.makeCar()); + mockHttpSession.setAttribute("user", new User()); + + when(postService.findAllByUserId(any(Integer.class))).thenReturn(List.of(post)); + + this.mockMvc.perform(get("/users/posts").session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attributeExists("posts")) + .andExpect(model().attribute("posts", List.of(post))) + .andExpect(status().isOk()) + .andExpect(view().name("users/posts")); + } + + @Test + void whenPostRequestUsersRegisterThenSaveUserAndRedirectToLoginPage() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.setAll(Map.of("email", "testEmail", "password", "testPassword")); + + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); + when(userService.save(any(User.class))).thenReturn(Optional.of(new User())); + + this.mockMvc.perform(post("/users/register").params(params)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/users/login")); + verify(userService).save(userCaptor.capture()); + assertThat(userCaptor.getValue().getEmail()).isEqualTo("testEmail"); + assertThat(userCaptor.getValue().getPassword()).isEqualTo("testPassword"); + } + + @Test + void whenPostRequestUsersRegisterWithWrongParamsThenGetErrorMessage() throws Exception { + when(userService.save(any())).thenReturn(Optional.empty()); + + this.mockMvc.perform(post("/users/register")) + .andDo(print()) + .andExpect(model().attribute("error", "Пользователь с таким email уже существует")) + .andExpect(status().isOk()) + .andExpect(view().name("users/register")); + } + + @Test + void whenPostRequestUsersLoginThenValidateUserAndRedirectIndexPage() throws Exception { + User user = testUtil.makeUser(); + MultiValueMap params = new LinkedMultiValueMap<>(); + params.setAll(Map.of("email", user.getEmail(), "password", user.getPassword())); + + when(userService.findByEmailAndPassword(any(), any())).thenReturn(Optional.of(user)); + + MvcResult mvcResult = mockMvc.perform(post("/users/login").params(params)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/")) + .andReturn(); + assertThat(mvcResult.getRequest().getSession().getAttribute("user")).isEqualTo(user); + } + + @Test + void whenPostRequestUsersLoginWithWrongParamsThenGetErrorMessage() throws Exception { + when(userService.findByEmailAndPassword(any(), any())).thenReturn(Optional.empty()); + + this.mockMvc.perform(post("/users/login")) + .andDo(print()) + .andExpect(model().attribute("error", "Email или пароль введены не верно!")) + .andExpect(status().isOk()) + .andExpect(view().name("users/login")); + } + + @Test + void whenPostRequestUsersUpdateThenUpdateUserAndInvalidateAndRedirectLoginPage() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.setAll(Map.of("name", "testName", "phone", "testPhone")); + User user = new User(); + user.setEmail("email"); + user.setPassword("password"); + mockHttpSession.setAttribute("user", user); + + ArgumentCaptor userCaptor = ArgumentCaptor.forClass(User.class); + when(userService.update(any(User.class))).thenReturn(true); + + assertThat(mockHttpSession.isInvalid()).isFalse(); + this.mockMvc.perform(post("/users/update").params(params).session(mockHttpSession)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/users/login")); + verify(userService).update(userCaptor.capture()); + User capturedUser = userCaptor.getValue(); + assertThat(capturedUser.getEmail()).isEqualTo(user.getEmail()); + assertThat(capturedUser.getPassword()).isEqualTo(user.getPassword()); + assertThat(capturedUser.getName()).isEqualTo("testName"); + assertThat(capturedUser.getPhone()).isEqualTo("testPhone"); + assertThat(mockHttpSession.isInvalid()).isTrue(); + } + + @Test + void whenPostRequestUsersUpdateWithWrongParamsThenGetErrorMessage() throws Exception { + User user = new User(); + user.setEmail("email"); + user.setPassword("password"); + mockHttpSession.setAttribute("user", user); + + when(userService.update(any(User.class))).thenReturn(false); + + this.mockMvc.perform(post("/users/update").session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attribute("error", "Ошибка при обновлении данных пользователя.")) + .andExpect(status().isOk()) + .andExpect(view().name("users/update")); + } + + @Test + void whenPostRequestUsersDeleteThenDeleteUserWithPostsAndInvalidateAndRedirectIndexPage() + throws Exception { + User user = new User(); + user.setEmail("email"); + user.setPassword("password"); + mockHttpSession.setAttribute("user", user); + + assertThat(mockHttpSession.isInvalid()).isFalse(); + this.mockMvc.perform(post("/users/delete").param("password", "password").session(mockHttpSession)) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(view().name("redirect:/")); + assertThat(mockHttpSession.isInvalid()).isTrue(); + verify(postService).deleteAllByUser(user); + verify(userService).deleteByEmailAndPassword(user.getEmail(), user.getPassword()); + } + + @Test + void whenPostRequestUsersDeleteWithWrongPasswordThenGetErrorMessage() throws Exception { + User user = new User(); + user.setEmail("email"); + user.setPassword("password"); + mockHttpSession.setAttribute("user", user); + + this.mockMvc.perform(post("/users/delete").param("password", "pass").session(mockHttpSession)) + .andDo(print()) + .andExpect(model().attribute("error", + "Введенный пароль не совпадает с паролем пользователя.")) + .andExpect(status().isOk()) + .andExpect(view().name("users/update")); + } + +} \ No newline at end of file diff --git a/src/test/java/cars/util/ControllerTestUtil.java b/src/test/java/cars/util/ControllerTestUtil.java new file mode 100644 index 0000000..16faddb --- /dev/null +++ b/src/test/java/cars/util/ControllerTestUtil.java @@ -0,0 +1,64 @@ +package cars.util; + +import java.time.LocalDateTime; +import ru.job4j.cars.model.*; + +public class ControllerTestUtil { + + public User makeUser() { + User user = new User(); + user.setEmail("email"); + user.setPassword("password"); + user.setName("name"); + user.setPhone("phone"); + return user; + } + + public Car makeCar() { + Brand brand = new Brand(); + brand.setName("brand"); + CarModel model = new CarModel(); + model.setName("model"); + Body body = new Body(); + body.setName("body"); + FuelType fuelType = new FuelType(); + fuelType.setName("fuelType"); + EngineSize engineSize = new EngineSize(); + engineSize.setSize(1.1f); + Engine engine = new Engine(); + engine.setFuelType(fuelType); + engine.setEngineSize(engineSize); + Transmission transmission = new Transmission(); + transmission.setName("transmission"); + Color color = new Color(); + color.setName("color"); + Category category = new Category(); + category.setName("category"); + + Car car = new Car(); + car.setBrand(brand); + car.setCarModel(model); + car.setBody(body); + car.setEngine(engine); + car.setTransmission(transmission); + car.setColor(color); + car.setCategory(category); + car.setMileage(1); + car.setYear(2001); + car.setVin("Vin"); + + return car; + } + + public Post makePost(User user, Car car) { + Post post = new Post(); + post.setUser(user); + post.setCar(car); + post.setCreated(LocalDateTime.now()); + post.setDescription("description"); + post.setSold(false); + post.setPrice(1L); + return post; + } + +} \ No newline at end of file