From a234ea63303eaa199215fabf78be9392f4b4dc7b Mon Sep 17 00:00:00 2001 From: PavloSliepchenko Date: Tue, 7 May 2024 07:22:08 -0500 Subject: [PATCH] Added tests for controller --- pom.xml | 5 + .../controller/UserControllerTest.java | 215 ++++++++++++++++++ .../usersapi/service/UserServiceTest.java | 66 ++---- .../com/example/usersapi/util/TestUtil.java | 35 +++ 4 files changed, 278 insertions(+), 43 deletions(-) create mode 100644 src/test/java/com/example/usersapi/controller/UserControllerTest.java create mode 100644 src/test/java/com/example/usersapi/util/TestUtil.java diff --git a/pom.xml b/pom.xml index df858dd..c8ae2e1 100644 --- a/pom.xml +++ b/pom.xml @@ -57,6 +57,11 @@ org.hibernate.validator hibernate-validator + + junit + junit + test + diff --git a/src/test/java/com/example/usersapi/controller/UserControllerTest.java b/src/test/java/com/example/usersapi/controller/UserControllerTest.java new file mode 100644 index 0000000..f282f5e --- /dev/null +++ b/src/test/java/com/example/usersapi/controller/UserControllerTest.java @@ -0,0 +1,215 @@ +package com.example.usersapi.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.usersapi.dto.CreateUserRequestDto; +import com.example.usersapi.dto.UserPatchRequestDto; +import com.example.usersapi.dto.UserResponseDto; +import com.example.usersapi.dto.UserResponseDtoWrapper; +import com.example.usersapi.model.User; +import com.example.usersapi.service.impl.UserServiceImpl; +import com.example.usersapi.util.TestUtil; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.LocalDate; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +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.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@WebMvcTest(UserController.class) +class UserControllerTest { + private CreateUserRequestDto requestDto; + private UserResponseDto responseDto; + @Autowired + private MockMvc mvc; + @Autowired + private ObjectMapper objectMapper; + @MockBean + private UserServiceImpl userService; + + @BeforeEach + void init() { + requestDto = new CreateUserRequestDto( + "user@gmail.com", + "Bob", + "Jackson", + "01/02/1990", + "414 Union Ave, Brooklyn, NY 11211", + "(111) 111-1111" + ); + User user = TestUtil.getUserFromCreateUserDto(1L, requestDto); + responseDto = TestUtil.getResponseDtoFromUser(user); + } + + @Test + @DisplayName("Add a new user") + void addUser_ValidRequest_ShouldAddUser() throws Exception { + Mockito.when(userService.createUser(requestDto)) + .thenReturn(new UserResponseDtoWrapper<>(responseDto)); + String jasonObject = objectMapper.writeValueAsString(requestDto); + mvc.perform(post("/api/users") + .content(jasonObject) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.data.email").value(requestDto.email())) + .andExpect(jsonPath("$.data.address").value(requestDto.address())) + .andExpect(jsonPath("$.data.lastName").value(requestDto.lastName())) + .andExpect(jsonPath("$.data.birthDate").value(requestDto.birthDate())) + .andExpect(jsonPath("$.data.firstName").value(requestDto.firstName())) + .andExpect(jsonPath("$.data.phoneNumber").value(requestDto.phoneNumber())); + } + + @Test + @DisplayName("Patch user") + void patchUser_ValidRequest_ShouldPatchUserInfo() throws Exception { + UserPatchRequestDto patchRequestDto = + new UserPatchRequestDto(null, "Adam", null, null, null, "(111) 111-2222"); + responseDto.setFirstName(patchRequestDto.firstName()); + responseDto.setPhoneNumber(patchRequestDto.phoneNumber()); + String jasonObject = objectMapper.writeValueAsString(patchRequestDto); + Long userId = 1L; + Mockito.when(userService.patchUser(userId, patchRequestDto)) + .thenReturn(new UserResponseDtoWrapper<>(responseDto)); + + mvc.perform(patch("/api/users/" + userId) + .content(jasonObject) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.firstName").value(patchRequestDto.firstName())) + .andExpect(jsonPath("$.data.phoneNumber").value(patchRequestDto.phoneNumber())); + } + + @Test + @DisplayName("Update user") + void updateUser_ValidRequest_ShouldUpdateUserInfo() throws Exception { + Long userId = 1L; + Mockito.when(userService.updateUser(userId, requestDto)) + .thenReturn(new UserResponseDtoWrapper<>(responseDto)); + String jasonObject = objectMapper.writeValueAsString(requestDto); + mvc.perform(put("/api/users/" + userId) + .content(jasonObject) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.email").value(requestDto.email())) + .andExpect(jsonPath("$.data.address").value(requestDto.address())) + .andExpect(jsonPath("$.data.lastName").value(requestDto.lastName())) + .andExpect(jsonPath("$.data.birthDate").value(requestDto.birthDate())) + .andExpect(jsonPath("$.data.firstName").value(requestDto.firstName())) + .andExpect(jsonPath("$.data.phoneNumber").value(requestDto.phoneNumber())); + } + + @Test + @DisplayName("Delete user") + void deleteUserById_ValidRequest_ShouldDeleteUser() throws Exception { + Long userId = 1L; + mvc.perform(delete("/api/users/" + userId)) + .andExpect(status().isNoContent()); + } + + @Test + @DisplayName("Search for users in birth dates range") + void searchByBirthDates_ValidRequest_ShouldReturnListOfUsersInDatesRange() throws Exception { + User user2 = new User(); + user2.setId(2L); + user2.setFirstName("Kassandra"); + user2.setLastName("Hernandez"); + user2.setEmail("Kassandra@example.com"); + user2.setBirthDate(LocalDate.of(1985, 5, 15)); + + User user3 = new User(); + user3.setId(3L); + user3.setFirstName("William"); + user3.setLastName("Williamson"); + user3.setEmail("William@example.com"); + user3.setBirthDate(LocalDate.of(1988, 9, 20)); + + User user4 = new User(); + user4.setId(4L); + user4.setFirstName("Kevin"); + user4.setLastName("Thompson"); + user4.setEmail("Kevin@example.com"); + user4.setBirthDate(LocalDate.of(1995, 3, 10)); + + User user5 = new User(); + user5.setId(5L); + user5.setFirstName("Matt"); + user5.setLastName("Wallace"); + user5.setEmail("Matt@example.com"); + user5.setBirthDate(LocalDate.of(1992, 11, 28)); + + UserResponseDto responseDto3 = TestUtil.getResponseDtoFromUser(user3); + UserResponseDto responseDto4 = TestUtil.getResponseDtoFromUser(user4); + + String from = "02/03/1986"; + String to = "10/03/1995"; + Mockito.when(userService.searchByBirthDates(from, to)).thenReturn( + new UserResponseDtoWrapper<>(List.of(responseDto, responseDto3, responseDto4))); + String getUrl = "/api/users/search?fromDate=%s&toDate=%s"; + mvc.perform(get(String.format(getUrl, from, to))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()").value(3)) + .andExpect(jsonPath("$.data[0].firstName").value(responseDto.getFirstName())) + .andExpect(jsonPath("$.data[0].birthDate").value(responseDto.getBirthDate())) + .andExpect(jsonPath("$.data[0].email").value(responseDto.getEmail())) + .andExpect(jsonPath("$.data[1].firstName").value(responseDto3.getFirstName())) + .andExpect(jsonPath("$.data[1].birthDate").value(responseDto3.getBirthDate())) + .andExpect(jsonPath("$.data[1].email").value(responseDto3.getEmail())) + .andExpect(jsonPath("$.data[2].firstName").value(responseDto4.getFirstName())) + .andExpect(jsonPath("$.data[2].birthDate").value(responseDto4.getBirthDate())) + .andExpect(jsonPath("$.data[2].email").value(responseDto4.getEmail())); + + UserResponseDto responseDto2 = TestUtil.getResponseDtoFromUser(user2); + UserResponseDto responseDto5 = TestUtil.getResponseDtoFromUser(user5); + + from = "15/04/1985"; + to = "10/03/2000"; + Mockito.when(userService.searchByBirthDates(from, to)) + .thenReturn(new UserResponseDtoWrapper<>(List.of( + responseDto, responseDto2, responseDto3, responseDto4, responseDto5 + ))); + mvc.perform(get(String.format(getUrl, from, to))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()").value(5)) + .andExpect(jsonPath("$.data[0].firstName").value(responseDto.getFirstName())) + .andExpect(jsonPath("$.data[0].birthDate").value(responseDto.getBirthDate())) + .andExpect(jsonPath("$.data[0].email").value(responseDto.getEmail())) + .andExpect(jsonPath("$.data[1].firstName").value(responseDto2.getFirstName())) + .andExpect(jsonPath("$.data[1].birthDate").value(responseDto2.getBirthDate())) + .andExpect(jsonPath("$.data[1].email").value(responseDto2.getEmail())) + .andExpect(jsonPath("$.data[2].firstName").value(responseDto3.getFirstName())) + .andExpect(jsonPath("$.data[2].birthDate").value(responseDto3.getBirthDate())) + .andExpect(jsonPath("$.data[2].email").value(responseDto3.getEmail())) + .andExpect(jsonPath("$.data[3].firstName").value(responseDto4.getFirstName())) + .andExpect(jsonPath("$.data[3].birthDate").value(responseDto4.getBirthDate())) + .andExpect(jsonPath("$.data[3].email").value(responseDto4.getEmail())) + .andExpect(jsonPath("$.data[4].firstName").value(responseDto5.getFirstName())) + .andExpect(jsonPath("$.data[4].birthDate").value(responseDto5.getBirthDate())) + .andExpect(jsonPath("$.data[4].email").value(responseDto5.getEmail())); + + from = "15/04/1990"; + to = "10/03/2003"; + Mockito.when(userService.searchByBirthDates(from, to)) + .thenReturn(new UserResponseDtoWrapper<>(List.of(responseDto5))); + mvc.perform(get(String.format(getUrl, from, to))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.size()").value(1)) + .andExpect(jsonPath("$.data[0].firstName").value(responseDto5.getFirstName())) + .andExpect(jsonPath("$.data[0].birthDate").value(responseDto5.getBirthDate())) + .andExpect(jsonPath("$.data[0].email").value(responseDto5.getEmail())); + } +} diff --git a/src/test/java/com/example/usersapi/service/UserServiceTest.java b/src/test/java/com/example/usersapi/service/UserServiceTest.java index a57188c..29bea85 100644 --- a/src/test/java/com/example/usersapi/service/UserServiceTest.java +++ b/src/test/java/com/example/usersapi/service/UserServiceTest.java @@ -9,9 +9,9 @@ import com.example.usersapi.model.User; import com.example.usersapi.repository.UserRepository; import com.example.usersapi.service.impl.UserServiceImpl; +import com.example.usersapi.util.TestUtil; import java.lang.reflect.Field; import java.time.LocalDate; -import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Assertions; @@ -29,7 +29,6 @@ class UserServiceTest { private CreateUserRequestDto requestDto; private User user; private UserResponseDto responseDto; - private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); @Mock private UserRepository userRepository; @Mock @@ -47,8 +46,8 @@ void init() throws Exception { "414 Union Ave, Brooklyn, NY 11211", "(111) 111-1111" ); - user = getUserFromCreateUserDto(1L, requestDto); - responseDto = getResponseDtoFromUser(user); + user = TestUtil.getUserFromCreateUserDto(1L, requestDto); + responseDto = TestUtil.getResponseDtoFromUser(user); Field field = userService.getClass().getDeclaredField("minAge"); field.setAccessible(true); @@ -82,7 +81,7 @@ void createUser_AgeLessThan18_ThrowsException() { null ); - User user = getUserFromCreateUserDto(1L, requestDto); + User user = TestUtil.getUserFromCreateUserDto(1L, requestDto); Mockito.when(userMapper.toModel(requestDto)).thenReturn(user); Assertions.assertThrows(RegistrationException.class, @@ -103,7 +102,7 @@ void patchUser_ValidRequest_ShouldUpdateUserField() { updatedUser.setPhoneNumber(user.getPhoneNumber()); updatedUser.setBirthDate(user.getBirthDate()); - UserResponseDto updatedResponseDto = getResponseDtoFromUser(updatedUser); + UserResponseDto updatedResponseDto = TestUtil.getResponseDtoFromUser(updatedUser); Mockito.when(userRepository.findById(userId)).thenReturn(Optional.of(user)); Mockito.when(userRepository.save(user)).thenReturn(user); @@ -148,8 +147,8 @@ void updateUser_ValidRequest_ShouldUpdateAllUserInfo() { "(222) 222-2222" ); Long userId = 1L; - User updatedUser = getUserFromCreateUserDto(userId, requestDto); - UserResponseDto updatedResponseDto = getResponseDtoFromUser(updatedUser); + User updatedUser = TestUtil.getUserFromCreateUserDto(userId, requestDto); + UserResponseDto updatedResponseDto = TestUtil.getResponseDtoFromUser(updatedUser); Mockito.when(userRepository.existsById(Mockito.anyLong())).thenReturn(true); Mockito.when(userMapper.toModel(requestDto)).thenReturn(updatedUser); @@ -196,10 +195,10 @@ void searchByBirthDates_ValidRequest_ShouldReturnListOfUsersInDatesRange() { user5.setEmail("user5@example.com"); user5.setBirthDate(LocalDate.of(1992, 11, 28)); - UserResponseDto responseDto2 = getResponseDtoFromUser(user2); - UserResponseDto responseDto3 = getResponseDtoFromUser(user3); - UserResponseDto responseDto4 = getResponseDtoFromUser(user4); - UserResponseDto responseDto5 = getResponseDtoFromUser(user5); + UserResponseDto responseDto2 = TestUtil.getResponseDtoFromUser(user2); + UserResponseDto responseDto3 = TestUtil.getResponseDtoFromUser(user3); + UserResponseDto responseDto4 = TestUtil.getResponseDtoFromUser(user4); + UserResponseDto responseDto5 = TestUtil.getResponseDtoFromUser(user5); Mockito.when(userMapper.toDto(user)).thenReturn(responseDto); Mockito.when(userMapper.toDto(user2)).thenReturn(responseDto2); @@ -209,8 +208,10 @@ void searchByBirthDates_ValidRequest_ShouldReturnListOfUsersInDatesRange() { String from = "02/03/1986"; String to = "10/03/1995"; - Mockito.when(userRepository.findByBirthDateBetween(LocalDate.parse(from, formatter), - LocalDate.parse(to, formatter))).thenReturn(List.of(user, user3, user4)); + Mockito.when(userRepository.findByBirthDateBetween( + LocalDate.parse(from, TestUtil.FORMATTER), + LocalDate.parse(to, TestUtil.FORMATTER)) + ).thenReturn(List.of(user, user3, user4)); List expected = List.of(responseDto, responseDto3, responseDto4); List actual = userService.searchByBirthDates(from, to).getData(); Assertions.assertEquals(expected.size(), actual.size()); @@ -218,9 +219,10 @@ void searchByBirthDates_ValidRequest_ShouldReturnListOfUsersInDatesRange() { from = "15/04/1985"; to = "10/03/2000"; - Mockito.when(userRepository.findByBirthDateBetween(LocalDate.parse(from, formatter), - LocalDate.parse(to, formatter))) - .thenReturn(List.of(user, user2, user3, user4, user5)); + Mockito.when(userRepository.findByBirthDateBetween( + LocalDate.parse(from, TestUtil.FORMATTER), + LocalDate.parse(to, TestUtil.FORMATTER)) + ).thenReturn(List.of(user, user2, user3, user4, user5)); expected = List.of(responseDto, responseDto2, responseDto3, responseDto4, responseDto5); actual = userService.searchByBirthDates(from, to).getData(); Assertions.assertEquals(expected.size(), actual.size()); @@ -228,35 +230,13 @@ void searchByBirthDates_ValidRequest_ShouldReturnListOfUsersInDatesRange() { from = "15/04/1990"; to = "10/03/2003"; - Mockito.when(userRepository.findByBirthDateBetween(LocalDate.parse(from, formatter), - LocalDate.parse(to, formatter))).thenReturn(List.of(user5)); + Mockito.when(userRepository.findByBirthDateBetween( + LocalDate.parse(from, TestUtil.FORMATTER), + LocalDate.parse(to, TestUtil.FORMATTER)) + ).thenReturn(List.of(user5)); expected = List.of(responseDto5); actual = userService.searchByBirthDates(from, to).getData(); Assertions.assertEquals(expected.size(), actual.size()); Assertions.assertTrue(actual.containsAll(expected)); } - - private User getUserFromCreateUserDto(Long userId, CreateUserRequestDto requestDto) { - User resulUser = new User(); - resulUser.setId(userId); - resulUser.setEmail(requestDto.email()); - resulUser.setFirstName(requestDto.firstName()); - resulUser.setLastName(requestDto.lastName()); - resulUser.setBirthDate(LocalDate.parse(requestDto.birthDate(), formatter)); - resulUser.setAddress(requestDto.address()); - resulUser.setPhoneNumber(requestDto.phoneNumber()); - return resulUser; - } - - private UserResponseDto getResponseDtoFromUser(User user) { - UserResponseDto userResponseDto = new UserResponseDto(); - userResponseDto.setId(user.getId()); - userResponseDto.setEmail(user.getEmail()); - userResponseDto.setFirstName(user.getFirstName()); - userResponseDto.setLastName(user.getLastName()); - userResponseDto.setBirthDate(user.getBirthDate().format(formatter)); - userResponseDto.setAddress(user.getAddress()); - userResponseDto.setPhoneNumber(user.getPhoneNumber()); - return userResponseDto; - } } diff --git a/src/test/java/com/example/usersapi/util/TestUtil.java b/src/test/java/com/example/usersapi/util/TestUtil.java new file mode 100644 index 0000000..9861b62 --- /dev/null +++ b/src/test/java/com/example/usersapi/util/TestUtil.java @@ -0,0 +1,35 @@ +package com.example.usersapi.util; + +import com.example.usersapi.dto.CreateUserRequestDto; +import com.example.usersapi.dto.UserResponseDto; +import com.example.usersapi.model.User; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class TestUtil { + public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy"); + + public static User getUserFromCreateUserDto(Long userId, CreateUserRequestDto requestDto) { + User resulUser = new User(); + resulUser.setId(userId); + resulUser.setEmail(requestDto.email()); + resulUser.setFirstName(requestDto.firstName()); + resulUser.setLastName(requestDto.lastName()); + resulUser.setBirthDate(LocalDate.parse(requestDto.birthDate(), FORMATTER)); + resulUser.setAddress(requestDto.address()); + resulUser.setPhoneNumber(requestDto.phoneNumber()); + return resulUser; + } + + public static UserResponseDto getResponseDtoFromUser(User user) { + UserResponseDto userResponseDto = new UserResponseDto(); + userResponseDto.setId(user.getId()); + userResponseDto.setEmail(user.getEmail()); + userResponseDto.setFirstName(user.getFirstName()); + userResponseDto.setLastName(user.getLastName()); + userResponseDto.setBirthDate(user.getBirthDate().format(FORMATTER)); + userResponseDto.setAddress(user.getAddress()); + userResponseDto.setPhoneNumber(user.getPhoneNumber()); + return userResponseDto; + } +}