From 801939b77b8cdd26fe1943ce714bc4bc756107e0 Mon Sep 17 00:00:00 2001 From: AntonBabychP1T Date: Tue, 26 Dec 2023 16:08:21 +0200 Subject: [PATCH] Create test to ShoppingCartService, ShoppingCartController, ShoppingCartRepository and UserService --- .../controller/ShoppingCartController.java | 1 + .../bookstoreapp/model/ShoppingCart.java | 9 +- .../java/store/bookstoreapp/model/User.java | 8 +- .../ShoppingCartControllerTest.java | 200 ++++++++++++++++ .../ShoppingCartRepositoryTest.java | 54 +++++ .../service/ShoppingCartServiceTest.java | 223 ++++++++++++++++++ .../bookstoreapp/service/UserServiceTest.java | 110 +++++++++ .../shoppingcart/create-cart-item.sql | 1 + .../shoppingcart/delete-all-from-cartitem.sql | 2 + .../create-default-user-and-shoppingcart.sql | 2 + .../database/users/delete-all-users.sql | 5 + .../database/users/delete-default-user.sql | 1 + 12 files changed, 608 insertions(+), 8 deletions(-) create mode 100644 src/test/java/store/bookstoreapp/controller/ShoppingCartControllerTest.java create mode 100644 src/test/java/store/bookstoreapp/repository/ShoppingCartRepositoryTest.java create mode 100644 src/test/java/store/bookstoreapp/service/ShoppingCartServiceTest.java create mode 100644 src/test/java/store/bookstoreapp/service/UserServiceTest.java create mode 100644 src/test/resources/database/shoppingcart/create-cart-item.sql create mode 100644 src/test/resources/database/shoppingcart/delete-all-from-cartitem.sql create mode 100644 src/test/resources/database/users/create-default-user-and-shoppingcart.sql create mode 100644 src/test/resources/database/users/delete-all-users.sql create mode 100644 src/test/resources/database/users/delete-default-user.sql diff --git a/src/main/java/store/bookstoreapp/controller/ShoppingCartController.java b/src/main/java/store/bookstoreapp/controller/ShoppingCartController.java index a40f1bb..4644e45 100644 --- a/src/main/java/store/bookstoreapp/controller/ShoppingCartController.java +++ b/src/main/java/store/bookstoreapp/controller/ShoppingCartController.java @@ -30,6 +30,7 @@ public class ShoppingCartController { private final ShoppingCartService shoppingCartService; @PostMapping + @ResponseStatus(HttpStatus.CREATED) @Operation(summary = "Add book to shopping cart", description = "Create new cart item with book and quantity") @Parameter(name = "bookId", description = "id of the book", diff --git a/src/main/java/store/bookstoreapp/model/ShoppingCart.java b/src/main/java/store/bookstoreapp/model/ShoppingCart.java index 6ad31c3..3f2256b 100644 --- a/src/main/java/store/bookstoreapp/model/ShoppingCart.java +++ b/src/main/java/store/bookstoreapp/model/ShoppingCart.java @@ -12,12 +12,11 @@ import jakarta.persistence.Table; import java.util.HashSet; import java.util.Set; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; +import lombok.EqualsAndHashCode; @Entity -@Getter -@Setter +@Data @Table(name = "shopping_cards") public class ShoppingCart { @Id @@ -25,7 +24,9 @@ public class ShoppingCart { private Long id; @OneToOne @MapsId + @EqualsAndHashCode.Exclude private User user; + @EqualsAndHashCode.Exclude @OneToMany(mappedBy = "shoppingCart", cascade = CascadeType.ALL, orphanRemoval = true) private Set cartItems = new HashSet<>(); @Column(nullable = false) diff --git a/src/main/java/store/bookstoreapp/model/User.java b/src/main/java/store/bookstoreapp/model/User.java index 87c1771..2156fe4 100644 --- a/src/main/java/store/bookstoreapp/model/User.java +++ b/src/main/java/store/bookstoreapp/model/User.java @@ -13,15 +13,14 @@ import java.util.Collection; import java.util.HashSet; import java.util.Set; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; +import lombok.EqualsAndHashCode; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -@Getter -@Setter +@Data @SQLDelete(sql = "UPDATE books SET is_deleted = true WHERE id=?") @Where(clause = "is_deleted=false") @Entity @@ -47,6 +46,7 @@ public class User implements UserDetails { joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id") ) + @EqualsAndHashCode.Exclude private Set roles = new HashSet<>(); @Override diff --git a/src/test/java/store/bookstoreapp/controller/ShoppingCartControllerTest.java b/src/test/java/store/bookstoreapp/controller/ShoppingCartControllerTest.java new file mode 100644 index 0000000..7210241 --- /dev/null +++ b/src/test/java/store/bookstoreapp/controller/ShoppingCartControllerTest.java @@ -0,0 +1,200 @@ +package store.bookstoreapp.controller; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +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.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; +import javax.sql.DataSource; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.testcontainers.shaded.org.apache.commons.lang3.builder.EqualsBuilder; +import store.bookstoreapp.dto.cartitem.CartItemDto; +import store.bookstoreapp.dto.cartitem.CartItemRequestDto; +import store.bookstoreapp.dto.cartitem.QuantityDto; +import store.bookstoreapp.dto.shoppingcart.ShoppingCartDto; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ShoppingCartControllerTest { + + private static MockMvc mockMvc; + @Autowired + private ObjectMapper objectMapper; + + @BeforeAll + static void beforeAll( + @Autowired DataSource dataSource, + @Autowired WebApplicationContext applicationContext + ) throws SQLException { + mockMvc = MockMvcBuilders + .webAppContextSetup(applicationContext) + .apply(springSecurity()) + .build(); + teardown(dataSource); + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(true); + ScriptUtils.executeSqlScript( + connection, + new ClassPathResource("database/users/create-default-user-and-shoppingcart.sql") + ); + } + } + + @AfterAll + static void afterAll( + @Autowired DataSource dataSource + ) throws SQLException { + teardown(dataSource); + } + + static void teardown(DataSource dataSource) throws SQLException { + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(true); + ScriptUtils.executeSqlScript( + connection, new ClassPathResource("database/users/delete-all-users.sql") + ); + } + } + + @WithMockUser(username = "test@email.com", roles = "USER") + @Test + @Sql( + scripts = { + "classpath:database/books/add-default-book.sql", + }, + executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD + ) + @Sql( + scripts = { + "classpath:database/shoppingcart/delete-all-from-cartitem.sql", + "classpath:database/books/delete-default-book.sql" + }, + executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD + ) + @DisplayName("Verify addBookToShoppingCart() method works") + public void addBookToShoppingCart_ValidRequestDto_ReturnShoppingCartDto() throws Exception { + CartItemRequestDto requestDto = new CartItemRequestDto(4L, 2); + String jsonRequest = objectMapper.writeValueAsString(requestDto); + ShoppingCartDto expected = new ShoppingCartDto(); + expected.setUserId(1L); + CartItemDto cartItemDto = new CartItemDto(1L, 4L, "Valid Title", 2); + expected.setCartItems(List.of(cartItemDto)); + + MvcResult result = mockMvc.perform(post("/api/cart") + .content(jsonRequest) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andReturn(); + + ShoppingCartDto actual = objectMapper + .readValue(result.getResponse().getContentAsString(), ShoppingCartDto.class); + + Assertions.assertNotNull(actual); + EqualsBuilder.reflectionEquals(expected, actual); + } + + @WithMockUser(username = "test@email.com", roles = "USER") + @Test + @DisplayName("Verify getShoppingCart() method works") + public void getShippingCart_ValidEmail_ReturnShoppingCart() throws Exception { + ShoppingCartDto expected = new ShoppingCartDto(); + expected.setUserId(1L); + expected.setCartItems(Collections.emptyList()); + + MvcResult result = mockMvc.perform(get("/api/cart") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + ShoppingCartDto actual = objectMapper + .readValue(result.getResponse().getContentAsString(), ShoppingCartDto.class); + + Assertions.assertNotNull(actual); + EqualsBuilder.reflectionEquals(expected, actual); + } + + @WithMockUser(username = "test@email.com", roles = "USER") + @Test + @Sql( + scripts = { + "classpath:database/books/add-default-book.sql", + "classpath:database/shoppingcart/create-cart-item.sql", + + }, + executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD + ) + @Sql( + scripts = { + "classpath:database/shoppingcart/delete-all-from-cartitem.sql", + "classpath:database/books/delete-default-book.sql", + }, + executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD + ) + @DisplayName("Verify deleteItemFromShoppingCart() method works") + public void deleteItemFromShoppingCart_ValidCardItemInDb_StatusNoContent() throws Exception { + mockMvc.perform(delete("/api/cart/cart-items/{id}", 1L) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + } + + @WithMockUser(username = "test@email.com", roles = "USER") + @Test + @Sql( + scripts = { + "classpath:database/books/add-default-book.sql", + "classpath:database/shoppingcart/create-cart-item.sql", + + }, + executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD + ) + @Sql( + scripts = { + "classpath:database/shoppingcart/delete-all-from-cartitem.sql", + "classpath:database/books/delete-default-book.sql", + }, + executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD + ) + @DisplayName("Verify updateQuantity() method works") + public void updateQuantity_CartItemInDb_NewQuantityInCartItem() throws Exception { + QuantityDto quantityDto = new QuantityDto(4); + String jsonRequest = objectMapper.writeValueAsString(quantityDto); + ShoppingCartDto expected = new ShoppingCartDto(); + expected.setUserId(1L); + CartItemDto cartItemDto = new CartItemDto(1L, 4L, "Valid Title", 4); + expected.setCartItems(List.of(cartItemDto)); + + MvcResult result = mockMvc.perform(put("/api/cart/cart-items/{id}", 1L) + .content(jsonRequest) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + ShoppingCartDto actual = objectMapper + .readValue(result.getResponse().getContentAsString(), ShoppingCartDto.class); + + Assertions.assertNotNull(actual); + EqualsBuilder.reflectionEquals(expected, actual); + } +} + + diff --git a/src/test/java/store/bookstoreapp/repository/ShoppingCartRepositoryTest.java b/src/test/java/store/bookstoreapp/repository/ShoppingCartRepositoryTest.java new file mode 100644 index 0000000..f7453be --- /dev/null +++ b/src/test/java/store/bookstoreapp/repository/ShoppingCartRepositoryTest.java @@ -0,0 +1,54 @@ +package store.bookstoreapp.repository; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.util.Collections; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; +import store.bookstoreapp.model.ShoppingCart; +import store.bookstoreapp.model.User; +import store.bookstoreapp.repository.shoppingcart.ShoppingCartRepository; + +@DataJpaTest +@Sql( + scripts = {"classpath:database/users/delete-all-users.sql", + "classpath:database/users/create-default-user-and-shoppingcart.sql", + }, + executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD +) +@Sql( + scripts = "classpath:database/users/delete-all-users.sql", + executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD +) +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +public class ShoppingCartRepositoryTest { + + @Autowired + private ShoppingCartRepository shoppingCartRepository; + + @Test + @DisplayName("Verify getShoppingCartById() method works") + public void getShoppingCartById_ValidCartInDb_ReturnCart() { + User user = new User(); + user.setId(1L); + user.setPassword("Password"); + user.setEmail("test@email.com"); + user.setFirstName("Default"); + user.setLastName("User"); + user.setRoles(Collections.emptySet()); + user.setShippingAddress("DefaultAddress'"); + ShoppingCart expected = new ShoppingCart(); + expected.setCartItems(Collections.emptySet()); + expected.setUser(user); + expected.setId(1L); + + ShoppingCart actual = shoppingCartRepository.getShoppingCartById(1L); + + assertThat(actual).isNotNull(); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/src/test/java/store/bookstoreapp/service/ShoppingCartServiceTest.java b/src/test/java/store/bookstoreapp/service/ShoppingCartServiceTest.java new file mode 100644 index 0000000..9462119 --- /dev/null +++ b/src/test/java/store/bookstoreapp/service/ShoppingCartServiceTest.java @@ -0,0 +1,223 @@ +package store.bookstoreapp.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.math.BigDecimal; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import store.bookstoreapp.dto.book.BookDto; +import store.bookstoreapp.dto.cartitem.CartItemDto; +import store.bookstoreapp.dto.cartitem.CartItemRequestDto; +import store.bookstoreapp.dto.shoppingcart.ShoppingCartDto; +import store.bookstoreapp.mapper.BookMapper; +import store.bookstoreapp.mapper.CartItemMapper; +import store.bookstoreapp.mapper.ShoppingCartMapper; +import store.bookstoreapp.model.Book; +import store.bookstoreapp.model.CartItem; +import store.bookstoreapp.model.ShoppingCart; +import store.bookstoreapp.model.User; +import store.bookstoreapp.repository.cartitem.CartItemRepository; +import store.bookstoreapp.repository.shoppingcart.ShoppingCartRepository; +import store.bookstoreapp.repository.user.UserRepository; +import store.bookstoreapp.service.impl.ShoppingCartServiceImpl; + +@ExtendWith(MockitoExtension.class) +public class ShoppingCartServiceTest { + private static final Long VALID_ID = 1L; + private static final User DEFAULT_USER = createValidUser(); + private static final Book VALID_BOOK = createValidBook(); + private static final String VALID_EMAIL = "user@example.com"; + + @InjectMocks + private ShoppingCartServiceImpl shoppingCartService; + + @Mock + private ShoppingCartRepository shoppingCartRepository; + + @Mock + private ShoppingCartMapper shoppingCartMapper; + + @Mock + private CartItemRepository cartItemRepository; + + @Mock + private BookService bookService; + + @Mock + private BookMapper bookMapper; + + @Mock + private UserRepository userRepository; + + @Mock + private CartItemMapper cartItemMapper; + + private ShoppingCart validShoppingCart; + private CartItem validCartItem; + private CartItemDto validCartItemDto; + private ShoppingCartDto validShoppingCartDto; + + @BeforeAll + static void beforeAll() { + } + + private static User createValidUser() { + User user = new User(); + user.setId(VALID_ID); + user.setEmail(VALID_EMAIL); + user.setPassword("Password"); + user.setRoles(Collections.emptySet()); + user.setLastName("Last Name"); + user.setFirstName("First Name"); + user.setShippingAddress("Address"); + return user; + } + + private static Book createValidBook() { + Book book = new Book(); + book.setId(VALID_ID); + book.setAuthor("Valid Author"); + book.setTitle("Valid Title"); + book.setPrice(BigDecimal.valueOf(9.99)); + book.setIsbn("ValidISNB"); + book.setDescription("Valid description"); + book.setCoverImage("Valid cover image"); + book.setCategories(Collections.emptySet()); + return book; + } + + @BeforeEach + void setUp() { + validShoppingCart = createValidShoppingCart(); + validCartItem = createValidCartItem(); + validCartItemDto = createValidCartItemDto(); + validShoppingCartDto = createValidShoppingCartDto(); + } + + private ShoppingCartDto createValidShoppingCartDto() { + ShoppingCartDto shoppingCartDto = new ShoppingCartDto(); + shoppingCartDto.setUserId(VALID_ID); + shoppingCartDto.setId(VALID_ID); + shoppingCartDto.setCartItems(List.of(validCartItemDto)); + return shoppingCartDto; + } + + private CartItem createValidCartItem() { + CartItem cartItem = new CartItem(); + cartItem.setQuantity(2); + cartItem.setShoppingCart(validShoppingCart); + cartItem.setBook(VALID_BOOK); + cartItem.setId(VALID_ID); + return cartItem; + } + + private CartItemDto createValidCartItemDto() { + return new CartItemDto(VALID_ID, VALID_ID, VALID_BOOK.getTitle(), 1); + } + + private BookDto createValidBookDto() { + BookDto bookDto = new BookDto(); + bookDto.setId(VALID_ID); + bookDto.setAuthor("Valid Author"); + bookDto.setTitle("Valid Title"); + bookDto.setPrice(BigDecimal.valueOf(9.99)); + bookDto.setIsbn("ValidISNB"); + bookDto.setDescription("Valid description"); + bookDto.setCoverImage("Valid cover image"); + bookDto.setCategoryIds(Collections.emptySet()); + return bookDto; + } + + private ShoppingCart createValidShoppingCart() { + ShoppingCart shoppingCart = new ShoppingCart(); + shoppingCart.setId(VALID_ID); + shoppingCart.setUser(DEFAULT_USER); + shoppingCart.setCartItems(new HashSet<>()); + return shoppingCart; + } + + @Test + @DisplayName("Verify addBookToShoppingCart() method works") + public void addBookToShoppingCart_ValidRequestDto_ReturnShoppingCartDto() { + User user = new User(); + user.setId(VALID_ID); + ShoppingCart shoppingCart = createValidShoppingCart(); + shoppingCart.setUser(user); + when(userRepository.findByEmail(any(String.class))).thenReturn(Optional.of(user)); + when(shoppingCartRepository.getShoppingCartById(VALID_ID)).thenReturn(shoppingCart); + BookDto bookDto = createValidBookDto(); + when(bookService.findBookById(VALID_ID)).thenReturn(bookDto); + Book book = createValidBook(); + when(bookMapper.toModel(bookDto)).thenReturn(book); + CartItem cartItem = createValidCartItem(); + when(cartItemRepository.save(any(CartItem.class))).thenReturn(cartItem); + when(shoppingCartRepository.save(any(ShoppingCart.class))).thenReturn(shoppingCart); + ShoppingCartDto expectedShoppingCartDto = createValidShoppingCartDto(); + when(shoppingCartMapper.toDto(any(ShoppingCart.class))).thenReturn(expectedShoppingCartDto); + CartItemRequestDto requestDto = new CartItemRequestDto(VALID_ID, 1); + + ShoppingCartDto result = shoppingCartService.addBookToShoppingCart(requestDto, VALID_EMAIL); + + assertEquals(expectedShoppingCartDto, result); + } + + @Test + @DisplayName("Verify getShoppingCart() method works") + public void getShoppingCart_ValidEmail_ReturnShoppingCartDto() { + when(userRepository.findByEmail(VALID_EMAIL)).thenReturn(Optional.of(DEFAULT_USER)); + when(shoppingCartRepository.getShoppingCartById(DEFAULT_USER.getId())) + .thenReturn(validShoppingCart); + when(shoppingCartMapper.toDto(validShoppingCart)).thenReturn(validShoppingCartDto); + + ShoppingCartDto actual = shoppingCartService.getShoppingCart(VALID_EMAIL); + + assertEquals(actual, validShoppingCartDto); + } + + @Test + @DisplayName("Verify deleteItemFromShoppingCart() method works") + public void deleteItemFromShoppingCart_ValidIdAndEmail_CallDeleteById() { + shoppingCartService.deleteItemFromShoppingCart(VALID_ID, VALID_EMAIL); + + verify(cartItemRepository).deleteById(VALID_ID); + } + + @Test + @DisplayName("Verify updateQuantity() method updates the quantity of a cart item") + public void updateQuantity_ValidIdAndQuantity_UpdatesCartItem() { + Integer newQuantity = 3; + CartItemDto cartItemDto = createValidCartItemDto(); + CartItemDto expectedCartItemDto + = new CartItemDto( + cartItemDto.id(), + cartItemDto.bookId(), + cartItemDto.bookTitle(), + newQuantity); + when(userRepository.findByEmail(VALID_EMAIL)).thenReturn(Optional.of(DEFAULT_USER)); + when(shoppingCartRepository.getShoppingCartById(DEFAULT_USER.getId())) + .thenReturn(validShoppingCart); + validShoppingCart.getCartItems().add(validCartItem); + when(cartItemRepository.save(validCartItem)).thenReturn(validCartItem); + when(cartItemMapper.toDto(validCartItem)).thenReturn(expectedCartItemDto); + + CartItemDto actualCartItemDto = shoppingCartService + .updateQuantity(VALID_ID, newQuantity, VALID_EMAIL); + + assertEquals(expectedCartItemDto, actualCartItemDto); + assertEquals(newQuantity, actualCartItemDto.quantity()); + verify(cartItemRepository).save(validCartItem); + } +} diff --git a/src/test/java/store/bookstoreapp/service/UserServiceTest.java b/src/test/java/store/bookstoreapp/service/UserServiceTest.java new file mode 100644 index 0000000..afd0dde --- /dev/null +++ b/src/test/java/store/bookstoreapp/service/UserServiceTest.java @@ -0,0 +1,110 @@ +package store.bookstoreapp.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.Optional; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.crypto.password.PasswordEncoder; +import store.bookstoreapp.dto.user.UserRegistrationRequestDto; +import store.bookstoreapp.dto.user.UserResponseDto; +import store.bookstoreapp.mapper.UserMapper; +import store.bookstoreapp.model.ShoppingCart; +import store.bookstoreapp.model.User; +import store.bookstoreapp.repository.shoppingcart.ShoppingCartRepository; +import store.bookstoreapp.repository.user.UserRepository; +import store.bookstoreapp.service.impl.UserServiceImpl; + +@ExtendWith(MockitoExtension.class) +public class UserServiceTest { + private static final String VALID_EMAIL = "test@email.com"; + private static final String VALID_PASSWORD = "Password"; + private static final String VALID_FIRST_NAME = "First Name"; + private static final String VALID_LAST_NAME = "Last Name"; + private static final String VALID_ADDRESS = "Address"; + private static final Long VALID_ID = 1L; + @InjectMocks + private UserServiceImpl userService; + + @Mock + private UserRepository userRepository; + + @Mock + private UserMapper userMapper; + + @Mock + private PasswordEncoder passwordEncoder; + + @Mock + private ShoppingCartRepository shoppingCartRepository; + + private User createValidUser() { + User user = new User(); + user.setId(VALID_ID); + user.setEmail(VALID_EMAIL); + user.setPassword(VALID_PASSWORD); + user.setRoles(Collections.emptySet()); + user.setLastName(VALID_LAST_NAME); + user.setFirstName(VALID_FIRST_NAME); + user.setShippingAddress(VALID_FIRST_NAME); + user.setRoles(Collections.emptySet()); + return user; + } + + private UserRegistrationRequestDto createValiduserRegistrationRequestDto() { + UserRegistrationRequestDto userRegistrationRequestDto = new UserRegistrationRequestDto(); + userRegistrationRequestDto.setEmail(VALID_EMAIL); + userRegistrationRequestDto.setPassword(VALID_PASSWORD); + userRegistrationRequestDto.setRepeatPassword(VALID_PASSWORD); + userRegistrationRequestDto.setFirstName(VALID_FIRST_NAME); + userRegistrationRequestDto.setLastName(VALID_LAST_NAME); + userRegistrationRequestDto.setShippingAddress(VALID_ADDRESS); + return userRegistrationRequestDto; + } + + private UserResponseDto createValidUserResponseDto() { + UserResponseDto userResponseDto = new UserResponseDto(); + userResponseDto.setEmail(VALID_EMAIL); + userResponseDto.setFirstName(VALID_FIRST_NAME); + userResponseDto.setLastName(VALID_LAST_NAME); + userResponseDto.setId(VALID_ID); + userResponseDto.setShippingAddress(VALID_ADDRESS); + return userResponseDto; + } + + @Test + @DisplayName("Verify registerNewShoppingCart() method works") + public void registerNewShoppingCart_ValidShoppingCart_CallSave() { + User user = createValidUser(); + ShoppingCart shoppingCart = new ShoppingCart(); + shoppingCart.setUser(user); + + userService.registerNewShoppingCart(user); + + verify(shoppingCartRepository).save(shoppingCart); + } + + @Test + @DisplayName("Verify register() method works") + public void register_ValidUserRegistrationRequestDto_ReturnUserResponseDto() { + UserRegistrationRequestDto requestDto = createValiduserRegistrationRequestDto(); + User user = createValidUser(); + UserResponseDto expected = createValidUserResponseDto(); + when(userRepository.findByEmail(requestDto.getEmail())).thenReturn(Optional.empty()); + when(userRepository.save(user)).thenReturn(user); + when(userMapper.toModel(requestDto)).thenReturn(user); + when(passwordEncoder.encode(requestDto.getPassword())).thenReturn("HashedPassword"); + when(userMapper.toDto(user)).thenReturn(expected); + + UserResponseDto actual = userService.register(requestDto); + + assertEquals(expected, actual); + } +} diff --git a/src/test/resources/database/shoppingcart/create-cart-item.sql b/src/test/resources/database/shoppingcart/create-cart-item.sql new file mode 100644 index 0000000..b461f02 --- /dev/null +++ b/src/test/resources/database/shoppingcart/create-cart-item.sql @@ -0,0 +1 @@ +INSERT INTO cards_items (shopping_cart_id, book_id, quantity, is_deleted) VALUES (1,4,2,0); \ No newline at end of file diff --git a/src/test/resources/database/shoppingcart/delete-all-from-cartitem.sql b/src/test/resources/database/shoppingcart/delete-all-from-cartitem.sql new file mode 100644 index 0000000..19cc7f6 --- /dev/null +++ b/src/test/resources/database/shoppingcart/delete-all-from-cartitem.sql @@ -0,0 +1,2 @@ +DELETE FROM cards_items; +ALTER TABLE cards_items AUTO_INCREMENT = 1; \ No newline at end of file diff --git a/src/test/resources/database/users/create-default-user-and-shoppingcart.sql b/src/test/resources/database/users/create-default-user-and-shoppingcart.sql new file mode 100644 index 0000000..bc9a196 --- /dev/null +++ b/src/test/resources/database/users/create-default-user-and-shoppingcart.sql @@ -0,0 +1,2 @@ +INSERT INTO users (email, password, first_name, last_name, shipping_address,is_deleted) VALUES ('test@email.com','Password', 'Default', 'User', 'DefaultAddress',0); +INSERT INTO shopping_cards (user_id,is_deleted) VALUES (1,0); \ No newline at end of file diff --git a/src/test/resources/database/users/delete-all-users.sql b/src/test/resources/database/users/delete-all-users.sql new file mode 100644 index 0000000..97a1ee1 --- /dev/null +++ b/src/test/resources/database/users/delete-all-users.sql @@ -0,0 +1,5 @@ +DELETE FROM users_roles WHERE user_id IN (SELECT id FROM users); +DELETE FROM users; +ALTER TABLE users AUTO_INCREMENT = 1; +ALTER TABLE shopping_cards AUTO_INCREMENT = 1; +ALTER TABLE cards_items AUTO_INCREMENT = 1; \ No newline at end of file diff --git a/src/test/resources/database/users/delete-default-user.sql b/src/test/resources/database/users/delete-default-user.sql new file mode 100644 index 0000000..605fb25 --- /dev/null +++ b/src/test/resources/database/users/delete-default-user.sql @@ -0,0 +1 @@ +DELETE FROM users where email = 'test@email.com'; \ No newline at end of file