From 8fd5e4db67fde0ee00622f5924b37b3e918d187a Mon Sep 17 00:00:00 2001 From: khanhtranduy <130121475+khanhtranduy@users.noreply.github.com> Date: Fri, 21 Jun 2024 11:21:49 +0700 Subject: [PATCH 1/2] Refactor existing test cases --- .../db/changelog/db.changelog-master.yaml | 4 +- .../com/yas/cart/service/CartServiceTest.java | 87 ++- .../src/test/resources/application.properties | 9 +- .../viewmodel/order/OrderItemPostVm.java | 3 + .../order/viewmodel/order/OrderPostVm.java | 2 + .../db/changelog/db.changelog-master.yaml | 4 +- .../yas/order/service/OrderServiceTest.java | 90 ++- .../src/test/resources/application.properties | 15 +- .../db/changelog/db.changelog-master.yaml | 4 +- product/pom.xml | 5 + .../db/changelog/db.changelog-master.yaml | 4 +- .../yas/product/config/SecurityConfig.java | 19 - .../controller/BrandControllerTest.java | 242 ++++--- .../controller/CategoryControllerTest.java | 237 ++++--- .../ProductAttributeControllerTest.java | 306 ++++++--- .../ProductAttributeGroupControllerTest.java | 346 +++++----- .../ProductAttributeValueControllerTest.java | 259 ++++--- .../ProductOptionControllerTest.java | 173 +++-- .../ProductOptionValueControllerTest.java | 137 ++-- .../com/yas/product/model/ProductTest.java | 20 - .../product/service/CategoryServiceTest.java | 64 +- .../product/service/ProductServiceTest.java | 645 +++++------------- .../service/ProductTemplateServiceTest.java | 255 +++---- .../src/test/resources/application.properties | 18 +- promotion/pom.xml | 5 + .../repository/PromotionRepository.java | 4 +- .../promotion/service/PromotionService.java | 2 +- .../service/PromotionServiceTest.java | 65 +- .../src/test/resources/application.properties | 19 +- .../com/yas/rating/config/SecurityConfig.java | 18 - .../java/com/yas/rating/model/RatingTest.java | 20 - .../yas/rating/service/RatingServiceTest.java | 174 +++-- .../src/test/resources/application.properties | 17 +- tax/src/test/resources/application.properties | 15 +- 34 files changed, 1598 insertions(+), 1689 deletions(-) delete mode 100644 product/src/test/java/com/yas/product/config/SecurityConfig.java delete mode 100644 product/src/test/java/com/yas/product/model/ProductTest.java delete mode 100644 rating/src/test/java/com/yas/rating/config/SecurityConfig.java delete mode 100644 rating/src/test/java/com/yas/rating/model/RatingTest.java diff --git a/cart/src/main/resources/db/changelog/db.changelog-master.yaml b/cart/src/main/resources/db/changelog/db.changelog-master.yaml index 56378094be..419ad29d64 100644 --- a/cart/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/cart/src/main/resources/db/changelog/db.changelog-master.yaml @@ -2,6 +2,4 @@ databaseChangeLog: - includeAll: path: db/changelog/ddl/ - includeAll: - path: db/changelog/data/ -# - includeAll: -# path: db/changelog/eventuate-dll/ \ No newline at end of file + path: db/changelog/data/ \ No newline at end of file diff --git a/cart/src/test/java/com/yas/cart/service/CartServiceTest.java b/cart/src/test/java/com/yas/cart/service/CartServiceTest.java index c1bb3a24ee..5d63e7b834 100644 --- a/cart/src/test/java/com/yas/cart/service/CartServiceTest.java +++ b/cart/src/test/java/com/yas/cart/service/CartServiceTest.java @@ -1,78 +1,67 @@ package com.yas.cart.service; +import com.yas.cart.CartApplication; import com.yas.cart.model.Cart; import com.yas.cart.model.CartItem; import com.yas.cart.repository.CartItemRepository; import com.yas.cart.repository.CartRepository; -import com.yas.cart.viewmodel.CartGetDetailVm; import com.yas.cart.viewmodel.CartListVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; -import java.util.HashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertEquals; +@SpringBootTest(classes = CartApplication.class) class CartServiceTest { - CartRepository cartRepository; - CartItemRepository cartItemRepository; - CartService cartService; - ProductService productService; - - CartGetDetailVm cartGetDetailVm; + @Autowired + private CartRepository cartRepository; + @Autowired + private CartItemRepository cartItemRepository; + @MockBean + private ProductService productService; + @Autowired + private CartService cartService; Cart cart1; Cart cart2; - List carts; - - Authentication authentication; @BeforeEach void setUp() { - cartRepository = mock(CartRepository.class); - cartItemRepository = mock(CartItemRepository.class); - productService = mock(ProductService.class); - cartService = new CartService( - cartRepository, - cartItemRepository, - productService); + cart1 = cartRepository.save(Cart + .builder().customerId("customer-1").build()); + cart2 = cartRepository.save(Cart + .builder().customerId("customer-2").build()); - cartGetDetailVm = new CartGetDetailVm(1L, "customerId",null, null); + CartItem cartItem1 = new CartItem(); + cartItem1.setProductId(1L); + cartItem1.setQuantity(2); + cartItem1.setCart(cart1); + CartItem cartItem2 = new CartItem(); + cartItem2.setProductId(2L); + cartItem2.setQuantity(3); + cartItem2.setCart(cart2); - HashSet cartItemList = new HashSet<>(); - cartItemList.add(new CartItem(1L, null, 1L, null, 1)); - cartItemList.add(new CartItem(2L, null, 2L, null, 2)); - cart1 = new Cart(1L, "customer-1", null,cartItemList); - cart2 = new Cart(2L, "customer-2",null, null); - carts = List.of(cart1, cart2); + cartItemRepository.saveAll(List.of(cartItem1, cartItem2)); + } - //Security config - authentication = mock(Authentication.class); - Mockito.when(authentication.getName()).thenReturn("Name"); - SecurityContextHolder.getContext().setAuthentication(authentication); + @AfterEach + void tearDown() { + cartItemRepository.deleteAll(); + cartRepository.deleteAll(); } @Test - void getCarts_ExistProductsInDatabase_Success() { - //given - List cartListVmExpected = List.of( - new CartListVm(1L, "customer-1"), - new CartListVm(2L, "customer-2") - ); - when(cartRepository.findAll()).thenReturn(carts); - - //when + void getCarts_ExistInDatabase_Success() { List cartListVmActual = cartService.getCarts(); - - //then - assertThat(cartListVmActual).hasSameSizeAs(cartListVmExpected); - assertThat(cartListVmActual.get(0)).isEqualTo(cartListVmExpected.get(0)); - assertThat(cartListVmActual.get(1)).isEqualTo(cartListVmExpected.get(1)); - + assertEquals(2, cartListVmActual.size()); + for(CartListVm cartListVm : cartListVmActual) { + assertThat(cartListVm.customerId().startsWith("customer-")); + } } } diff --git a/cart/src/test/resources/application.properties b/cart/src/test/resources/application.properties index 13df26f522..658f52dec5 100644 --- a/cart/src/test/resources/application.properties +++ b/cart/src/test/resources/application.properties @@ -9,12 +9,11 @@ spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false # Setting Spring profile spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.cart \ No newline at end of file +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test \ No newline at end of file diff --git a/order/src/main/java/com/yas/order/viewmodel/order/OrderItemPostVm.java b/order/src/main/java/com/yas/order/viewmodel/order/OrderItemPostVm.java index ab780545f8..c6e24d7d70 100644 --- a/order/src/main/java/com/yas/order/viewmodel/order/OrderItemPostVm.java +++ b/order/src/main/java/com/yas/order/viewmodel/order/OrderItemPostVm.java @@ -1,7 +1,10 @@ package com.yas.order.viewmodel.order; +import lombok.Builder; + import java.math.BigDecimal; +@Builder public record OrderItemPostVm( Long productId, String productName, diff --git a/order/src/main/java/com/yas/order/viewmodel/order/OrderPostVm.java b/order/src/main/java/com/yas/order/viewmodel/order/OrderPostVm.java index b0d7e3de05..0c7f081f2c 100644 --- a/order/src/main/java/com/yas/order/viewmodel/order/OrderPostVm.java +++ b/order/src/main/java/com/yas/order/viewmodel/order/OrderPostVm.java @@ -5,10 +5,12 @@ import com.yas.order.model.enumeration.EPaymentStatus; import com.yas.order.viewmodel.orderaddress.OrderAddressPostVm; import jakarta.validation.constraints.NotNull; +import lombok.Builder; import java.math.BigDecimal; import java.util.List; +@Builder public record OrderPostVm( String checkoutId, String email, diff --git a/order/src/main/resources/db/changelog/db.changelog-master.yaml b/order/src/main/resources/db/changelog/db.changelog-master.yaml index 56378094be..419ad29d64 100644 --- a/order/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/order/src/main/resources/db/changelog/db.changelog-master.yaml @@ -2,6 +2,4 @@ databaseChangeLog: - includeAll: path: db/changelog/ddl/ - includeAll: - path: db/changelog/data/ -# - includeAll: -# path: db/changelog/eventuate-dll/ \ No newline at end of file + path: db/changelog/data/ \ No newline at end of file diff --git a/order/src/test/java/com/yas/order/service/OrderServiceTest.java b/order/src/test/java/com/yas/order/service/OrderServiceTest.java index a851c8f01b..8a53ce5c9d 100644 --- a/order/src/test/java/com/yas/order/service/OrderServiceTest.java +++ b/order/src/test/java/com/yas/order/service/OrderServiceTest.java @@ -1,20 +1,106 @@ package com.yas.order.service; +import com.yas.order.OrderApplication; +import com.yas.order.model.Order; +import com.yas.order.model.OrderItem; +import com.yas.order.repository.OrderItemRepository; +import com.yas.order.repository.OrderRepository; +import com.yas.order.viewmodel.order.OrderItemPostVm; +import com.yas.order.viewmodel.order.OrderPostVm; +import com.yas.order.viewmodel.order.OrderVm; +import com.yas.order.viewmodel.orderaddress.OrderAddressPostVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import javax.swing.text.html.Option; +import java.math.BigDecimal; +import java.util.Arrays; import java.util.List; +import java.util.Optional; -import static org.mockito.Mockito.mock; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +@SpringBootTest(classes = OrderApplication.class) class OrderServiceTest { + + @MockBean + private ProductService productService; + @MockBean + private CartService cartService; + @Autowired + private OrderItemRepository orderItemRepository; + @Autowired + private OrderRepository orderRepository; + @Autowired + private OrderService orderService; + private OrderItemPostVm orderItemPostVm; + private OrderAddressPostVm orderAddressPostVm; + private OrderPostVm orderPostVm; + + @BeforeEach void setUp() { + orderItemPostVm = OrderItemPostVm.builder() + .productId(1L).productName("abc") + .quantity(1).productPrice(BigDecimal.TEN) + .discountAmount(BigDecimal.ONE).taxAmount(BigDecimal.ONE).taxPercent(BigDecimal.ONE) + .build(); + orderAddressPostVm = OrderAddressPostVm.builder() + .contactName("contactName").phone("phone").addressLine1("addressLine1").addressLine2("addressLine2") + .city("city").zipCode("zipCode").districtId(1L).districtName("districtName") + .stateOrProvinceId(1L).stateOrProvinceName("stateOrProvinceName") + .countryId(1L).countryName("countryName") + .build(); + orderPostVm = OrderPostVm.builder() + .checkoutId("1").email("abc@gmail.com") + .orderItemPostVms(Arrays.asList(orderItemPostVm)) + .billingAddressPostVm(orderAddressPostVm) + .shippingAddressPostVm(orderAddressPostVm) + .build(); + } + + @AfterEach + void tearDown() { + orderItemRepository.deleteAll(); + orderRepository.deleteAll(); } @Test - void Test() { + void testCreateOrder_successful() { + + OrderVm orderVm = orderService.createOrder(orderPostVm); + + Optional orderOptional = orderRepository.findById(orderVm.id()); + assertTrue(orderOptional.isPresent()); + Order orderDB = orderOptional.get(); + assertEquals("abc@gmail.com", orderDB.getEmail()); + assertEquals(1, orderDB.getOrderItems().size()); + assertEquals("abc", orderDB.getOrderItems().stream().findFirst().get().getProductName()); + } + + @Test + void testCreateOrder_RemoteServiceThrowsException_RollbackOrder() { + doThrow(new RuntimeException()).when(productService).subtractProductStockQuantity(any(OrderVm.class)); + try { + orderService.createOrder(orderPostVm); + } catch (Exception e) { + + } + List orders = orderRepository.findAll(); + assertEquals(0, orders.size()); + List orderItems = orderItemRepository.findAll(); + assertEquals(0, orderItems.size()); } } diff --git a/order/src/test/resources/application.properties b/order/src/test/resources/application.properties index ed149c7b53..d6aef75330 100644 --- a/order/src/test/resources/application.properties +++ b/order/src/test/resources/application.properties @@ -2,6 +2,9 @@ server.servlet.context-path=/v1 server.port=8085 +# Setting Spring profile +spring.profiles.active=test + spring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=VALUE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa @@ -9,12 +12,8 @@ spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false -# Setting Spring profile -spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true - -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.order \ No newline at end of file +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test \ No newline at end of file diff --git a/payment/src/main/resources/db/changelog/db.changelog-master.yaml b/payment/src/main/resources/db/changelog/db.changelog-master.yaml index 56378094be..419ad29d64 100644 --- a/payment/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/payment/src/main/resources/db/changelog/db.changelog-master.yaml @@ -2,6 +2,4 @@ databaseChangeLog: - includeAll: path: db/changelog/ddl/ - includeAll: - path: db/changelog/data/ -# - includeAll: -# path: db/changelog/eventuate-dll/ \ No newline at end of file + path: db/changelog/data/ \ No newline at end of file diff --git a/product/pom.xml b/product/pom.xml index 2d36c8ed2f..7a5942e42e 100644 --- a/product/pom.xml +++ b/product/pom.xml @@ -61,6 +61,11 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + org.springframework.boot spring-boot-starter-data-jpa diff --git a/product/src/main/resources/db/changelog/db.changelog-master.yaml b/product/src/main/resources/db/changelog/db.changelog-master.yaml index 56378094be..419ad29d64 100644 --- a/product/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/product/src/main/resources/db/changelog/db.changelog-master.yaml @@ -2,6 +2,4 @@ databaseChangeLog: - includeAll: path: db/changelog/ddl/ - includeAll: - path: db/changelog/data/ -# - includeAll: -# path: db/changelog/eventuate-dll/ \ No newline at end of file + path: db/changelog/data/ \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/config/SecurityConfig.java b/product/src/test/java/com/yas/product/config/SecurityConfig.java deleted file mode 100644 index 1dff03cd9e..0000000000 --- a/product/src/test/java/com/yas/product/config/SecurityConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.yas.product.config; - -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; - -@TestConfiguration -public class SecurityConfig { - - @Bean - public WebSecurityCustomizer webSecurityCustomizer() { - return web -> web.ignoring() - .requestMatchers(HttpMethod.POST, "/backoffice/**") - .requestMatchers(HttpMethod.PUT, "/backoffice/**") - .requestMatchers(HttpMethod.GET, "/backoffice/**") - .requestMatchers(HttpMethod.DELETE, "/backoffice/**"); - } -} diff --git a/product/src/test/java/com/yas/product/controller/BrandControllerTest.java b/product/src/test/java/com/yas/product/controller/BrandControllerTest.java index 6bed630236..7ec401a08b 100644 --- a/product/src/test/java/com/yas/product/controller/BrandControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/BrandControllerTest.java @@ -1,127 +1,205 @@ package com.yas.product.controller; -import com.yas.product.exception.BadRequestException; -import com.yas.product.exception.NotFoundException; +import com.yas.product.ProductApplication; import com.yas.product.model.Brand; import com.yas.product.model.Product; -import com.yas.product.service.BrandService; import com.yas.product.repository.BrandRepository; +import com.yas.product.repository.ProductRepository; import com.yas.product.viewmodel.brand.BrandPostVm; import com.yas.product.viewmodel.brand.BrandVm; -import org.junit.jupiter.api.Assertions; +import com.yas.product.viewmodel.error.ErrorVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponentsBuilder; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import java.util.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.*; +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.BodyInserters; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc public class BrandControllerTest { + @Autowired private BrandRepository brandRepository; - private BrandService brandService; - private BrandController brandController; + @Autowired + private ProductRepository productRepository; + @Autowired + private WebTestClient webTestClient; private final Brand brand1 = new Brand(); + private Long brandId; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String STORE_FRONT_URL = "/storefront/brands"; + private final String BACK_OFFICE_URL = "/backoffice/brands"; + private Long invalidId = 9999L; @BeforeEach - void init(){ - brandRepository = mock(BrandRepository.class); - brandService = mock(BrandService.class); - brandController = new BrandController(brandRepository, brandService ); - brand1.setId(1L); - brand1.setName("dien thoai"); - brand1.setSlug("dien-thoai"); + void setup() { + brand1.setName("iphone13"); + brand1.setSlug("iphone-13"); brand1.setProducts(List.of()); + brandId = brandRepository.save(brand1).getId(); + } + + @AfterEach + void tearDown() { + productRepository.deleteAll(); + brandRepository.deleteAll(); } @Test - void listBrands_ReturnList_Success() { - Brand brand2 = new Brand(); - brand2.setId(2L); - brand2.setName("ao quan"); - brand2.setSlug("ao-quan"); - List brands= new ArrayList<>(Arrays.asList(brand1,brand2)); - when(brandRepository.findAll()).thenReturn(brands); - ResponseEntity> result = brandController.listBrands(); - assertThat(result.getStatusCode(),is(HttpStatus.OK)); - assertEquals(Objects.requireNonNull(result.getBody()).size(), brands.size()); - for(int i=0;i> result = + webTestClient.get().uri(STORE_FRONT_URL) + .accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk() + .expectBodyList(BrandVm.class) + .returnResult(); + List brandVms = result.getResponseBody(); + assertEquals(1, brandVms.size()); + assertEquals(brand1.getName(), brandVms.get(0).name()); + assertEquals(brand1.getSlug(), brandVms.get(0).slug()); } @Test - void getBrand_FindIdBrand_ThrowException(){ - when(brandRepository.findById(1L)).thenReturn(Optional.empty()); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> brandController.getBrand(1L)); - assertThat(exception.getMessage(),is("Brand 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void listBrands_BackOfficeReturnList_Success() { + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(BrandVm.class) + .returnResult(); + List brandVms = result.getResponseBody(); + assertEquals(1, brandVms.size()); + assertEquals(brand1.getName(), brandVms.get(0).name()); + assertEquals(brand1.getSlug(), brandVms.get(0).slug()); } @Test - void getBrand_FindIdBrand_Success(){ - when(brandRepository.findById(1L)).thenReturn(Optional.of(brand1)); - ResponseEntity result = brandController.getBrand(1L); - assertEquals(Objects.requireNonNull(result.getBody()).name(), brand1.getName()); - assertEquals(result.getBody().slug(), brand1.getSlug()); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void getBrand_FindIdBrand_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Brand 9999 is not found", Collections.emptyList()); + + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void createBrand_SaveBrandPostVm_Success(){ - BrandPostVm brandPostVm = new BrandPostVm("samsung","samsung", false); - Brand savedBrand = brandPostVm.toModel(); - savedBrand.setId(1L); - when(brandService.create(any())).thenReturn(savedBrand); - ResponseEntity result = brandController.createBrand(brandPostVm, UriComponentsBuilder.fromPath("/brands/{id}")); - assertEquals(Objects.requireNonNull(result.getBody()).name(), brandPostVm.name()); - assertEquals(result.getBody().slug(), brandPostVm.slug()); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void getBrand_FindIdBrand_Success() { + EntityExchangeResult result = webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", brandId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(BrandVm.class) + .returnResult(); + BrandVm brandVm = result.getResponseBody(); + assertNotNull(brandVm); + assertEquals(brand1.getName(), brandVm.name()); + assertEquals(brand1.getSlug(), brandVm.slug()); } @Test - void updateBrand_FindIdBrandUpdate_ThrowException(){ - BrandPostVm brandPostVm = new BrandPostVm("samsung","samsung", false); - when(brandService.update(any(), anyLong())).thenThrow(new NotFoundException("Brand 1 is not found")); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> brandController.updateBrand(1L, brandPostVm)); - assertThat(exception.getMessage(),is("Brand 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createBrand_SaveBrandPostVm_Success() { + BrandPostVm brandPostVm = new BrandPostVm("samsung", "samsung", true); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(brandPostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(BrandVm.class) + .returnResult(); + BrandVm brandVm = result.getResponseBody(); + assertNotNull(brandVm); + assertEquals(brandPostVm.name(), brandVm.name()); + assertEquals(brandPostVm.slug(), brandVm.slug()); + } + + @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) + void updateBrand_FindIdBrandUpdate_404NotFound() { + BrandPostVm brandPostVm = new BrandPostVm("samsung", "samsung", true); + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Brand 9999 is not found", Collections.emptyList()); + + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(brandPostVm)) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void updateBrand_UpdateBrand_Success(){ - BrandPostVm brandPostVm = new BrandPostVm("samsung","samsung", false); - when(brandRepository.findById(1L)).thenReturn(Optional.of(brand1)); - brandRepository.findById(1L).get().setSlug(brandPostVm.slug()); - brandRepository.findById(1L).get().setName(brandPostVm.name()); - when(brandRepository.save(brand1)).thenReturn(brand1); - assertThat(brand1.getName(), is(brandPostVm.name())); - assertThat(brand1.getSlug(), is(brandPostVm.slug())); - ResponseEntity result = brandController.updateBrand(1L,brandPostVm); - assertThat(result.getStatusCode(),is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void updateBrand_UpdateBrand_Success() { + BrandPostVm brandPostVm = new BrandPostVm("samsung", "samsung", true); + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", brandId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(brandPostVm)) + .exchange() + .expectStatus().isNoContent(); + Optional brand = brandRepository.findById(brandId); + assertTrue(brand.isPresent()); + assertEquals("samsung", brand.get().getName()); + assertEquals("samsung", brand.get().getSlug()); } @Test - void deleteBrand_ValidCategory_Success(){ - when(brandRepository.findById(1L)).thenReturn(Optional.of(brand1)); - ResponseEntity result = brandController.deleteBrand(1L); - verify(brandRepository).deleteById(1L); - assertThat(result.getStatusCode(),is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteBrand_ValidCategory_Success() { + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", brandId).accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNoContent(); + Optional brand = brandRepository.findById(brandId); + assertFalse(brand.isPresent()); } @Test - void deleteBrand_NotFoundCategory_ThrowNotFoundException(){ - when(brandRepository.findById(1L)).thenReturn(Optional.empty()); - assertThrows(NotFoundException.class, () -> brandController.deleteBrand(1L)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteBrand_NotFoundCategory_404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Brand 9999 is not found", Collections.emptyList()); + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange().expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void deleteBrand_CategoryContainsProducts_ThrowBadRequestException(){ - brand1.setProducts(List.of(new Product())); - when(brandRepository.findById(1L)).thenReturn(Optional.of(brand1)); - assertThrows(BadRequestException.class, () -> brandController.deleteBrand(1L)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteBrand_CategoryContainsProducts_400BadRequest() { + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Please make sure this brand don't contains any product", Collections.emptyList()); + Product product = Product.builder() + .name(String.format("product")) + .slug(String.format("slug")) + .isAllowedToOrder(true) + .isPublished(true) + .isFeatured(true) + .isVisibleIndividually(true) + .stockTrackingEnabled(true) + .brand(brand1) + .build(); + productRepository.save(product); + brand1.setProducts(List.of(product)); + brandRepository.save(brand1).getId(); + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", brandId) + .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } } \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java b/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java index b4c678cb47..14bbc68e50 100644 --- a/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java @@ -1,156 +1,169 @@ package com.yas.product.controller; -import com.yas.product.exception.BadRequestException; -import com.yas.product.exception.NotFoundException; +import com.yas.product.ProductApplication; import com.yas.product.model.Category; import com.yas.product.repository.CategoryRepository; -import com.yas.product.service.CategoryService; -import com.yas.product.viewmodel.ImageVm; import com.yas.product.viewmodel.category.CategoryGetDetailVm; import com.yas.product.viewmodel.category.CategoryGetVm; import com.yas.product.viewmodel.category.CategoryPostVm; +import com.yas.product.viewmodel.error.ErrorVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.BodyInserters; -import java.security.Principal; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.Objects; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc class CategoryControllerTest { - CategoryRepository categoryRepository; - CategoryService categoryService; - CategoryController categoryController; - List categories; - Category category; - Principal principal; - CategoryPostVm categoryPostVm; - UriComponentsBuilder uriComponentsBuilder; + @Autowired + private CategoryRepository categoryRepository; + @Autowired + private WebTestClient webTestClient; + private Category category; + private Long categoryId; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String STORE_FRONT_URL = "/storefront/categories"; + private final String BACK_OFFICE_URL = "/backoffice/categories"; + private final Long invalidId = 9999L; @BeforeEach void setUp() { - uriComponentsBuilder = mock(UriComponentsBuilder.class); - categoryService = mock(CategoryService.class); - principal = mock(Principal.class); - categories = new ArrayList<>(); - categoryRepository = mock(CategoryRepository.class); - categoryController = new CategoryController(categoryRepository, categoryService); category = new Category(); - category.setId(1L); - category.setName("hô hô"); - category.setSlug("ho-ho"); - category.setMetaKeyword("ho ho"); - category.setMetaDescription("ho ho"); + category.setName("laptop"); + category.setSlug("laptop-slug"); + category.setMetaKeyword("keyword"); + category.setMetaDescription("description"); category.setDisplayOrder((short) 0); - categories.add(category); - when(principal.getName()).thenReturn("user"); + categoryId = categoryRepository.save(category).getId(); } - @Test - void ListCategories_ValidListCategoryGetVM_Success() { - ImageVm categoryImage = new ImageVm(1L, "url"); - List expect = List.of( - new CategoryGetVm(1L, "hô hô", "ho-ho", -1, categoryImage) - ); - when(categoryService.getCategories()).thenReturn(expect); - ResponseEntity> actual = categoryController.listCategories(); - assertThat(Objects.requireNonNull(actual.getBody()).size()).isEqualTo(expect.size()); - assertThat(actual.getBody().get(0).id()).isEqualTo(expect.get(0).id()); + @AfterEach + void tearDown() { + categoryRepository.deleteAll(); } @Test - void getCategory_NotFoundCategoryGetDetailVM_ThrowNotFoundException() { - when(categoryService.getCategoryById(2L)).thenThrow(NotFoundException.class); - assertThrows(NotFoundException.class, () -> categoryController.getCategory(2L)); + void getListCategories_StoreFront_Success() { + EntityExchangeResult> result = + webTestClient.get().uri(STORE_FRONT_URL) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(CategoryGetVm.class) + .returnResult(); + List brandVms = result.getResponseBody(); + assertEquals(1, brandVms.size()); + assertEquals(category.getName(), brandVms.get(0).name()); + assertEquals(category.getSlug(), brandVms.get(0).slug()); } @Test - void getCategory_ValidCategoryGetDetailVM_Success() { - CategoryGetDetailVm expect = CategoryGetDetailVm.fromModel(category); - when(categoryService.getCategoryById(1L)).thenReturn(expect); - ResponseEntity actual = categoryController.getCategory(1L); - assertEquals(Objects.requireNonNull(actual.getBody()).Id(), expect.Id()); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void getListCategories_Backoffice_Success() { + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL).accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(CategoryGetVm.class) + .returnResult(); + List categoryGetVms = result.getResponseBody(); + assertEquals(1, categoryGetVms.size()); + assertEquals(category.getName(), categoryGetVms.get(0).name()); + assertEquals(category.getSlug(), categoryGetVms.get(0).slug()); } @Test - void createCategory_ValidCategoryWithOutParentId_Success() { - categoryPostVm = new CategoryPostVm( - "name", - "slug", - "description", - null, - "", - "", - (short) 0, - false, - 1L - ); - Category savedCategory = mockSavedCategory(); - when(categoryService.create(any())).thenReturn(savedCategory); - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - UriComponents uriComponents = mock(UriComponents.class); - when(uriComponentsBuilder.replacePath("/categories/{id}")).thenReturn(newUriComponentsBuilder); - when(newUriComponentsBuilder.buildAndExpand(savedCategory.getId())).thenReturn(uriComponents); - categoryController.createCategory(categoryPostVm, uriComponentsBuilder, principal); - assertThat(savedCategory.getName()).isEqualTo(categoryPostVm.name()); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void getCategory_NotFoundCategoryGetDetailVM_404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Category 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } - private Category mockSavedCategory() { - Category savedCategory = new Category(); - savedCategory.setName(categoryPostVm.name()); - savedCategory.setId(1L); - savedCategory.setDisplayOrder((short) 1); + @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) + void getCategory_ValidCategoryGetDetailVM_Success() { + EntityExchangeResult result = + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", categoryId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(CategoryGetDetailVm.class) + .returnResult(); + CategoryGetDetailVm categoryGetDetailVm = result.getResponseBody(); + assertNotNull(categoryGetDetailVm); + assertEquals(category.getName(), categoryGetDetailVm.name()); + assertEquals(category.getSlug(), categoryGetDetailVm.slug()); + } - return savedCategory; + @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createCategory_ValidCategoryWithOutParentId_Success() { + CategoryPostVm categoryPostVm = new CategoryPostVm( + "laptop2", "laptop-slug2", "description2", + null, "", "", (short) 0, true, 1L); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(categoryPostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(CategoryGetDetailVm.class) + .returnResult(); + CategoryGetDetailVm categoryGetDetailVm = result.getResponseBody(); + assertNotNull(categoryGetDetailVm); + assertEquals(categoryPostVm.name(), categoryGetDetailVm.name()); + assertEquals(categoryPostVm.slug(), categoryGetDetailVm.slug()); } @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) void createCategory_ValidCategoryWithParentId_Success() { - categoryPostVm = new CategoryPostVm( - "name", - "slug", - "description", - 1L, - "", - "", - (short) 0, - false, - 1L - ); - Category savedCategory = mockSavedCategory(); - when(categoryService.create(any())).thenReturn(savedCategory); - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - UriComponents uriComponents = mock(UriComponents.class); - when(uriComponentsBuilder.replacePath("/categories/{id}")).thenReturn(newUriComponentsBuilder); - when(newUriComponentsBuilder.buildAndExpand(savedCategory.getId())).thenReturn(uriComponents); - categoryController.createCategory(categoryPostVm - , uriComponentsBuilder, principal); - assertThat(savedCategory.getName()).isEqualTo(categoryPostVm.name()); + CategoryPostVm categoryPostVm = new CategoryPostVm( + "laptop2", "laptop-slug2", "description2", + categoryId, "", "", (short) 0, true, 1L); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(categoryPostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(CategoryGetDetailVm.class) + .returnResult(); + CategoryGetDetailVm categoryGetDetailVm = result.getResponseBody(); + assertNotNull(categoryGetDetailVm); + assertEquals(categoryPostVm.name(), categoryGetDetailVm.name()); + assertEquals(categoryPostVm.slug(), categoryGetDetailVm.slug()); } @Test - void createCategory_ValidCategoryWithNotFoundParentId_ThrowNotFoundException() { - categoryPostVm = new CategoryPostVm( - "name", - "slug", - "description", - 2L, - "", - "", - (short) 0, - false, - 1L - ); - when(categoryService.create(any())).thenThrow(BadRequestException.class); - assertThrows(BadRequestException.class, () -> categoryController.createCategory(categoryPostVm - , uriComponentsBuilder, principal)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createCategory_ValidCategoryWithNotFoundParentId_400BadRequest() { + CategoryPostVm categoryPostVm = new CategoryPostVm( + "laptop2", "laptop-slug2", "description2", + 9999L, "", "", (short) 0, true, 1L); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Parent category 9999 is not found", Collections.emptyList()); + webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(categoryPostVm)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } } \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java index 4dba09d0f4..3ff14af8e0 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java @@ -1,165 +1,249 @@ package com.yas.product.controller; -import com.yas.product.exception.BadRequestException; -import com.yas.product.exception.NotFoundException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yas.product.ProductApplication; +import com.yas.product.model.Brand; +import com.yas.product.model.Product; import com.yas.product.model.attribute.ProductAttribute; import com.yas.product.model.attribute.ProductAttributeGroup; import com.yas.product.model.attribute.ProductAttributeValue; import com.yas.product.repository.ProductAttributeGroupRepository; import com.yas.product.repository.ProductAttributeRepository; +import com.yas.product.repository.ProductAttributeValueRepository; +import com.yas.product.repository.ProductRepository; +import com.yas.product.viewmodel.category.CategoryGetDetailVm; +import com.yas.product.viewmodel.category.CategoryGetVm; +import com.yas.product.viewmodel.error.ErrorVm; import com.yas.product.viewmodel.productattribute.ProductAttributeGetVm; import com.yas.product.viewmodel.productattribute.ProductAttributePostVm; -import com.yas.product.service.ProductAttributeService; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; - -import java.security.Principal; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.web.reactive.function.BodyInserters; + +import java.util.*; + +import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc class ProductAttributeControllerTest { - ProductAttributeRepository productAttributeRepository; - ProductAttributeService productAttributeService; - ProductAttributeController productAttributeController; - UriComponentsBuilder uriComponentsBuilder; - Principal principal; - ProductAttribute productAttribute = new ProductAttribute(); - - ProductAttributeGroup productAttributeGroup = new ProductAttributeGroup(); + @Autowired + private ProductAttributeRepository productAttributeRepository; + @Autowired + private ProductAttributeGroupRepository productAttributeGroupRepository; + @Autowired + private ProductRepository productRepository; + @Autowired + private ProductAttributeValueRepository productAttributeValueRepository; + @Autowired + private WebTestClient webTestClient; + private Long productAttributeId; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String BACK_OFFICE_URL = "/backoffice/product-attribute"; + private ProductAttribute productAttribute; + private ProductAttributeGroup productAttributeGroup; + private Long invalidId = 9999L; @BeforeEach void setUp(){ - productAttributeRepository = mock(ProductAttributeRepository.class); - productAttributeService = mock(ProductAttributeService.class); - uriComponentsBuilder = mock(UriComponentsBuilder.class); - principal = mock(Principal.class); - productAttributeController = new ProductAttributeController(productAttributeRepository, - productAttributeService); - productAttributeGroup.setId(1L); + productAttributeGroup = new ProductAttributeGroup(); productAttributeGroup.setName("Computer"); - productAttribute.setId(1L); + productAttributeGroup = productAttributeGroupRepository.save(productAttributeGroup); + productAttribute = new ProductAttribute(); productAttribute.setName("Ram"); productAttribute.setProductAttributeGroup(productAttributeGroup); + productAttribute = productAttributeRepository.save(productAttribute); + productAttributeId = productAttribute.getId(); + } + + @AfterEach + void tearDown() { + productAttributeValueRepository.deleteAll(); + productRepository.deleteAll(); + productAttributeRepository.deleteAll(); + productAttributeGroupRepository.deleteAll(); } @Test - void listProductAttributes_ValidListProductAttributeGetVm_Success(){ - List listProductAttribute = List.of(productAttribute); - when(productAttributeRepository.findAll()).thenReturn(listProductAttribute); - ResponseEntity> result = productAttributeController.listProductAttributes(); - assertThat(result.getStatusCode(),is(HttpStatus.OK)); - assertEquals(Objects.requireNonNull(result.getBody()).size(), listProductAttribute.size()); - for(int i=0;i> result = + webTestClient.get().uri(BACK_OFFICE_URL) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(ProductAttributeGetVm.class) + .returnResult(); + List productAttributeGetVms = result.getResponseBody(); + assertEquals(1, productAttributeGetVms.size()); + assertEquals(productAttribute.getName(), productAttributeGetVms.get(0).name()); } @Test - void getProductAttribute_FinProductAttributeById_ThrowException(){ - when(productAttributeRepository.findById(1L)).thenReturn(Optional.empty()); - NotFoundException notFoundException = Assertions.assertThrows(NotFoundException.class, - () -> productAttributeController.getProductAttribute(1L)); - assertThat(notFoundException.getMessage(),is("Product attribute 1 is not found")); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void getProductAttribute_FinProductAttributeById_404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product attribute 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void getProductAttribute_FindProductAttribute_Success(){ - when(productAttributeRepository.findById(1L)).thenReturn(Optional.of(productAttribute)); - ResponseEntity result = productAttributeController.getProductAttribute(1L); - assertEquals(Objects.requireNonNull(result.getBody()).name(), productAttribute.getName()); - assertEquals(result.getBody().id(), productAttribute.getId()); - assertEquals(result.getBody().id(), productAttribute.getId()); - assertEquals(result.getBody().productAttributeGroup(), productAttribute.getProductAttributeGroup().getName()); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void getProductAttribute_FindProductAttribute_Success() { + EntityExchangeResult result = + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", productAttributeId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(ProductAttributeGetVm.class) + .returnResult(); + ProductAttributeGetVm productAttributeGetVm = result.getResponseBody(); + assertNotNull(productAttributeGetVm); + assertEquals(productAttribute.getName(), productAttributeGetVm.name()); } @Test - void createProductAttribute_FindIdProductAttributeGroup_ThrowException(){ - ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("Ram",1L); - when(productAttributeService.save(any())).thenThrow(new BadRequestException("Product attribute group 1 is not found")); - BadRequestException exception = Assertions.assertThrows(BadRequestException.class, - () -> productAttributeController.createProductAttribute(productAttributePostVm, UriComponentsBuilder.fromPath("/product-attribute/{id}"), principal)); - assertThat(exception.getMessage(),is("Product attribute group 1 is not found")); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void createProductAttribute_FindIdProductAttributeGroup_400BadRequest() { + ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("CPU", 9999L); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Product attribute group 9999 is not found", Collections.emptyList()); + webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributePostVm)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void createProductAttribute_ValidProductAttributeWithIdProductAttributeGroup_Success(){ - ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("Ram",1L); - ProductAttribute savedProductAttribute = new ProductAttribute(); - savedProductAttribute.setName(productAttributePostVm.name()); - savedProductAttribute.setId(1L); - ProductAttributeGroup group = new ProductAttributeGroup(); - group.setName("Computer"); - savedProductAttribute.setProductAttributeGroup(group); - when(productAttributeService.save(any())).thenReturn(savedProductAttribute); - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - UriComponents uriComponents = mock(UriComponents.class); - when(uriComponentsBuilder.replacePath("/product-attribute/{id}")).thenReturn(newUriComponentsBuilder); - when(newUriComponentsBuilder.buildAndExpand(savedProductAttribute.getId())).thenReturn(uriComponents); - ResponseEntity result = productAttributeController.createProductAttribute(productAttributePostVm - , uriComponentsBuilder, principal); - assertEquals(savedProductAttribute.getName(), productAttributePostVm.name()); - assertEquals(Objects.requireNonNull(result.getBody()).productAttributeGroup() , productAttributeGroup.getName() ); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void createProductAttribute_ValidProductAttributeWithIdProductAttributeGroup_Success() { + ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("CPU", productAttributeGroup.getId()); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributePostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(ProductAttributeGetVm.class) + .returnResult(); + ProductAttributeGetVm productAttributeGetVm = result.getResponseBody(); + assertNotNull(productAttributeGetVm); + assertEquals(productAttributePostVm.name(), productAttributeGetVm.name()); } @Test - void updateProductAttribute_FindIdProductAttribute_ThrowException(){ - ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("Ram",1L); - when(productAttributeService.update(any(), anyLong())).thenThrow(new NotFoundException("Product attribute 1 is not found")); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> productAttributeController.updateProductAttribute(1L,productAttributePostVm)); - assertThat(exception.getMessage(),is("Product attribute 1 is not found")); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void updateProductAttribute_FindIdProductAttribute_404NotFound() { + ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("CPU", productAttributeGroup.getId()); + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product attribute 9999 is not found", Collections.emptyList()); + + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributePostVm)) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } + @Test - void updateProductAttribute_FindProductAttributeGroupId_ThrowException(){ - ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("Ram",1L); - when(productAttributeService.update(any(), anyLong())).thenThrow(new BadRequestException("Product attribute group 1 is not found")); - BadRequestException exception = Assertions.assertThrows(BadRequestException.class, - () -> productAttributeController.updateProductAttribute(1L,productAttributePostVm)); - assertThat(exception.getMessage(),is("Product attribute group 1 is not found")); + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void updateProductAttribute_FindProductAttributeGroupId_400BadRequest() { + ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("CPU", invalidId); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Product attribute group 9999 is not found", Collections.emptyList()); + + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", productAttributeId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributePostVm)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); + } + @Test - void updateProductAttribute_ValidProductAttributePostVmWithProductAttributeGroupId_Success(){ - ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("Card",1L); - ProductAttribute savedProductAttribute = new ProductAttribute(); - savedProductAttribute.setName(productAttributePostVm.name()); - when(productAttributeService.update(any(), anyLong())).thenReturn(savedProductAttribute); - ResponseEntity result = productAttributeController.updateProductAttribute(1L,productAttributePostVm); - assertEquals(savedProductAttribute.getName(), productAttributePostVm.name()); - assertThat(result.getStatusCode(),is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void updateProductAttribute_ValidProductAttributePostVmWithProductAttributeGroupId_Success() { + ProductAttributePostVm productAttributePostVm = new ProductAttributePostVm("CPU", productAttributeGroup.getId()); + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", productAttributeId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributePostVm)) + .exchange() + .expectStatus().isNoContent(); + Optional optionalProductAttribute = productAttributeRepository.findById(productAttributeId); + assertTrue(optionalProductAttribute.isPresent()); + assertEquals(productAttributePostVm.name(), optionalProductAttribute.get().getName()); } @Test - void deleteProductAttribute_givenProductAttributeIdValid_thenSuccess(){ - when(productAttributeRepository.findById(1L)).thenReturn(Optional.of(productAttribute)); - ResponseEntity response = productAttributeController.deleteProductAttribute(1L); - verify(productAttributeRepository).deleteById(1L); - assertThat(response.getStatusCode(),is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteProductAttribute_givenProductAttributeIdValid_thenSuccess() { + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", productAttributeId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNoContent(); + Optional productAttribute = productAttributeRepository.findById(productAttributeId); + assertFalse(productAttribute.isPresent()); } @Test - void deleteProductAttribute_givenProductAttributeIdInvalid_thenThrowNotFoundException(){ - when(productAttributeRepository.findById(1L)).thenReturn(Optional.empty()); - assertThrows(NotFoundException.class, ()->productAttributeController.deleteProductAttribute(1L)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteProductAttribute_givenProductAttributeIdInvalid_thenReturn404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product attribute 9999 is not found", Collections.emptyList()); + + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void deleteProductAttribute_givenProductAttributeIdContainProductAttributeValue_thenThrowBadRequestException(){ - productAttribute.setAttributeValues(List.of(new ProductAttributeValue())); - when(productAttributeRepository.findById(1L)).thenReturn(Optional.of(productAttribute)); - assertThrows(BadRequestException.class, ()->productAttributeController.deleteProductAttribute(1L)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteProductAttribute_givenProductAttributeIdContainProductAttributeValue_thenReturn400BadRequest() throws Exception { + Product product = Product.builder() + .name(String.format("product")) + .slug(String.format("slug")) + .isAllowedToOrder(true) + .isPublished(true) + .isFeatured(true) + .isVisibleIndividually(true) + .stockTrackingEnabled(true) + .build(); + productRepository.save(product); + + ProductAttributeValue productAttributeValue = new ProductAttributeValue(); + productAttributeValue.setProduct(product); + productAttributeValue.setProductAttribute(productAttribute); + productAttributeValueRepository.save(productAttributeValue); + + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", + "Please make sure this Product Attribute doesn't exist in any Product Attribute Values", Collections.emptyList()); + + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", productAttributeId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } } diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java index b4e24f499a..b39e19bc1b 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java @@ -1,163 +1,183 @@ -//package com.yas.product.controller; -// -//import com.yas.product.model.attribute.ProductAttributeGroup; -//import com.yas.product.repository.ProductAttributeGroupRepository; -//import com.yas.product.viewmodel.error.ErrorVm; -//import com.yas.product.viewmodel.productattribute.ProductAttributeGroupPostVm; -//import com.yas.product.viewmodel.productattribute.ProductAttributeGroupVm; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.boot.test.context.SpringBootTest; -//import org.springframework.http.HttpStatus; -//import org.springframework.http.MediaType; -//import org.springframework.test.annotation.DirtiesContext; -//import org.springframework.test.web.reactive.server.WebTestClient; -//import org.springframework.web.reactive.function.BodyInserters; -// -//import java.util.ArrayList; -//import java.util.List; -// -//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -//@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) -//class ProductAttributeGroupControllerTest { -// -// @Autowired -// private WebTestClient webTestClient; -// -// @Autowired -// private ProductAttributeGroupRepository productAttributeGroupRepository; -// private ProductAttributeGroupVm productAttributeGroupVmExpected1; -// private List listProductAttributeGroupVmExpected; -// private Long validId; -// private Long invalidId; -// private ProductAttributeGroupPostVm productAttributeGroupPostVmValid; -// private ProductAttributeGroupPostVm productAttributeGroupPostVmInvalid; -// -// @BeforeEach -// void setUp() { -// ProductAttributeGroup productAttributeGroup1 = new ProductAttributeGroup(); -// ProductAttributeGroup productAttributeGroup2 = new ProductAttributeGroup(); -// productAttributeGroup1.setName("productAttributeGroupName1"); -// productAttributeGroup2.setName("productAttributeGroupName2"); -// productAttributeGroupRepository.saveAndFlush(productAttributeGroup1); -// productAttributeGroupRepository.saveAndFlush(productAttributeGroup2); -// -// productAttributeGroupVmExpected1 = new ProductAttributeGroupVm(1L, "productAttributeGroupName1"); -// listProductAttributeGroupVmExpected = new ArrayList<>(); -// listProductAttributeGroupVmExpected.addAll(List.of( -// new ProductAttributeGroupVm(1L, "productAttributeGroupName1"), -// new ProductAttributeGroupVm(2L, "productAttributeGroupName2"))); -// -// validId = 1L; -// invalidId = 3L; -// -// productAttributeGroupPostVmValid = new ProductAttributeGroupPostVm("productAttributeGroupName3"); -// productAttributeGroupPostVmInvalid = new ProductAttributeGroupPostVm(""); -// } -// -// @Test -// void listProductAttributeGroups_ReturnListProductAttributeGroupVm_Success() { -// webTestClient.get() -// .uri("/backoffice/product-attribute-groups") -// .exchange() -// .expectStatus().isOk() -// .expectBodyList(ProductAttributeGroupVm.class).isEqualTo(listProductAttributeGroupVmExpected); -// } -// -// @Test -// void getProductAttributeGroup_ReturnProductAttributeGroupVm_Success() { -// webTestClient.get() -// .uri("/backoffice/product-attribute-groups/{id}", validId) -// .exchange() -// .expectStatus().isOk() -// .expectBody(ProductAttributeGroupVm.class).isEqualTo(productAttributeGroupVmExpected1); -// } -// -// @Test -// void getProductAttributeGroup_ProductAttributeGroupIdIsInvalid_ThrowsNotFoundException() { -// ErrorVm errorVmExpected = new ErrorVm(HttpStatus.NOT_FOUND.toString(), "NotFound", -// String.format("Product attribute group %s is not found", invalidId)); -// -// webTestClient.get() -// .uri("/backoffice/product-attribute-groups/{id}", invalidId) -// .exchange() -// .expectStatus().isNotFound() -// .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); -// } -// -// @Test -// void createProductAttributeGroup_ReturnProductAttributeGroupVm_Success() { -// ProductAttributeGroupVm productAttributeGroupVmExpected3 = new ProductAttributeGroupVm(3L, "productAttributeGroupName3"); -// -// webTestClient.post() -// .uri("/backoffice/product-attribute-groups") -// .contentType(MediaType.APPLICATION_JSON) -// .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)) -// .exchange() -// .expectStatus().isCreated() -// .expectBody(ProductAttributeGroupVm.class).isEqualTo(productAttributeGroupVmExpected3); -// } -// -// @Test -// void createProductAttributeGroup_NameIsEmpty_ThrowsMethodArgumentNotValidException() { -// List fieldErrors = new ArrayList<>(); -// fieldErrors.add("name must not be empty"); -// ErrorVm errorVmExpected = new ErrorVm("400", "Bad Request", "Request information is not valid", fieldErrors); -// -// webTestClient.post() -// .uri("/backoffice/product-attribute-groups") -// .contentType(MediaType.APPLICATION_JSON) -// .body(BodyInserters.fromValue(productAttributeGroupPostVmInvalid)) -// .exchange() -// .expectStatus().isBadRequest() -// .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); -// } -// -// @Test -// void updateProductAttributeGroup_ProductAttributeGroupIdIsValid_Success() { -// webTestClient.put() -// .uri("/backoffice/product-attribute-groups/{id}", validId) -// .contentType(MediaType.APPLICATION_JSON) -// .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)) -// .exchange() -// .expectStatus().isNoContent(); -// } -// -// @Test -// void updateProductAttributeGroup_ProductAttributeGroupIdIsInvalid_ThrowsNotFoundException() { -// ErrorVm errorVmExpected = new ErrorVm(HttpStatus.NOT_FOUND.toString(), "NotFound", String.format("Product attribute group %s is not found", invalidId)); -// -// webTestClient.put() -// .uri("/backoffice/product-attribute-groups/{id}", invalidId) -// .contentType(MediaType.APPLICATION_JSON) -// .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)) -// .exchange() -// .expectStatus().isNotFound() -// .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); -// } -// -// @Test -// void updateProductAttributeGroup_ProductAttributeGroupNamIsEmpty_ThrowsMethodArgumentNotValidException() { -// List fieldErrors = new ArrayList<>(); -// fieldErrors.add("name must not be empty"); -// ErrorVm errorVmExpected = new ErrorVm("400", "Bad Request", "Request information is not valid", fieldErrors); -// -// webTestClient.put() -// .uri("/backoffice/product-attribute-groups/{id}", validId) -// .contentType(MediaType.APPLICATION_JSON) -// .body(BodyInserters.fromValue(productAttributeGroupPostVmInvalid)) -// .exchange() -// .expectStatus().isBadRequest() -// .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); -// } -// -// @Test -// void deleteProductAttributeGroup_givenProductAttributeGroupIsValid_thenSuccess(){ -// webTestClient.delete() -// .uri("/backoffice/product-attribute-groups/{id}", validId) -// .exchange() -// .expectStatus().isNoContent(); -// } -// -//} \ No newline at end of file +package com.yas.product.controller; + +import com.yas.product.ProductApplication; +import com.yas.product.model.attribute.ProductAttributeGroup; +import com.yas.product.repository.ProductAttributeGroupRepository; +import com.yas.product.viewmodel.error.ErrorVm; +import com.yas.product.viewmodel.productattribute.ProductAttributeGroupPostVm; +import com.yas.product.viewmodel.productattribute.ProductAttributeGroupVm; +import org.junit.jupiter.api.BeforeEach; +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.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.BodyInserters; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc +class ProductAttributeGroupControllerTest { + @Autowired + private WebTestClient webTestClient; + @Autowired + private ProductAttributeGroupRepository productAttributeGroupRepository; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String BACK_OFFICE_URL = "/backoffice/product-attribute-groups"; + private ProductAttributeGroup productAttributeGroup1; + private ProductAttributeGroup productAttributeGroup2; + private ProductAttributeGroupPostVm productAttributeGroupPostVmValid; + private ProductAttributeGroupPostVm productAttributeGroupPostVmInvalid; + private Long invalidId = 9999L; + + @BeforeEach + void setUp() { + productAttributeGroup1 = new ProductAttributeGroup(); + productAttributeGroup2 = new ProductAttributeGroup(); + productAttributeGroup1.setName("productAttributeGroupName1"); + productAttributeGroup2.setName("productAttributeGroupName2"); + productAttributeGroupRepository.saveAndFlush(productAttributeGroup1); + productAttributeGroupRepository.saveAndFlush(productAttributeGroup2); + } + + @BeforeEach + public void tearDown() { + productAttributeGroupRepository.deleteAll(); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void listProductAttributeGroups_ReturnListProductAttributeGroupVm_Success() { + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL) + .accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk() + .expectBodyList(ProductAttributeGroupVm.class) + .returnResult(); + List productAttributeGroupVms = result.getResponseBody(); + assertEquals(2, productAttributeGroupVms.size()); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void getProductAttributeGroup_ReturnProductAttributeGroupVm_Success() { + EntityExchangeResult result = + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", productAttributeGroup1.getId()) + .accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isOk() + .expectBody(ProductAttributeGroupVm.class) + .returnResult(); + ProductAttributeGroupVm productAttributeGroupVm = result.getResponseBody(); + assertNotNull(productAttributeGroupVm); + assertEquals(productAttributeGroup1.getId(), productAttributeGroupVm.id()); + assertEquals(productAttributeGroup1.getName(), productAttributeGroupVm.name()); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void getProductAttributeGroup_ProductAttributeGroupIdIsInvalid_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product attribute group 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON).exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); + } + + @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createProductAttributeGroup_ReturnProductAttributeGroupVm_Success() { + productAttributeGroupPostVmValid = new ProductAttributeGroupPostVm("productAttributeGroupName3"); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)).exchange() + .expectStatus().isCreated() + .expectBody(ProductAttributeGroupVm.class).returnResult(); + ProductAttributeGroupVm productAttributeGroupVm = result.getResponseBody(); + assertNotNull(productAttributeGroupVm); + assertEquals(productAttributeGroupPostVmValid.name(), productAttributeGroupVm.name()); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void createProductAttributeGroup_NameIsEmpty_Return400BadRequest() { + List fieldErrors = new ArrayList<>(); + fieldErrors.add("name must not be blank"); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Request information is not valid", fieldErrors); + productAttributeGroupPostVmInvalid = new ProductAttributeGroupPostVm(""); + webTestClient + .post() + .uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeGroupPostVmInvalid)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void updateProductAttributeGroup_ProductAttributeGroupIdIsValid_Success() { + productAttributeGroupPostVmValid = new ProductAttributeGroupPostVm("productAttributeGroupName3"); + webTestClient + .put() + .uri(BACK_OFFICE_URL + "/{id}", productAttributeGroup1.getId()) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)) + .exchange() + .expectStatus().isNoContent(); + + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void updateProductAttributeGroup_ProductAttributeGroupIdIsInvalid_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm(HttpStatus.NOT_FOUND.toString(), "Not Found", String.format("Product attribute group %s is not found", invalidId)); + productAttributeGroupPostVmValid = new ProductAttributeGroupPostVm("productAttributeGroupName3"); + webTestClient.put() + .uri(BACK_OFFICE_URL + "/{id}", invalidId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeGroupPostVmValid)) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void updateProductAttributeGroup_ProductAttributeGroupNamIsEmpty_Return400BadRequest() { + List fieldErrors = new ArrayList<>(); + fieldErrors.add("name must not be blank"); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Request information is not valid", fieldErrors); + productAttributeGroupPostVmInvalid = new ProductAttributeGroupPostVm(""); + webTestClient.put() + .uri(BACK_OFFICE_URL + "/{id}", productAttributeGroup1.getId()) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeGroupPostVmInvalid)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); + } + + @Test + @WithMockUser(username = USERNAME ,roles= {ROLE}) + void deleteProductAttributeGroup_givenProductAttributeGroupIsValid_thenSuccess(){ + webTestClient.delete() + .uri(BACK_OFFICE_URL + "/{id}", productAttributeGroup1.getId()) + .exchange() + .expectStatus().isNoContent(); + Optional result = productAttributeGroupRepository.findById(productAttributeGroup1.getId()); + assertFalse(result.isPresent()); + } + +} \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java index 35bdfc72b3..f31cc811b4 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java @@ -1,168 +1,201 @@ package com.yas.product.controller; -import com.yas.product.exception.BadRequestException; -import com.yas.product.exception.NotFoundException; +import com.yas.product.ProductApplication; import com.yas.product.model.Product; import com.yas.product.model.attribute.ProductAttribute; import com.yas.product.model.attribute.ProductAttributeGroup; import com.yas.product.model.attribute.ProductAttributeValue; +import com.yas.product.repository.ProductAttributeGroupRepository; import com.yas.product.repository.ProductAttributeRepository; import com.yas.product.repository.ProductAttributeValueRepository; import com.yas.product.repository.ProductRepository; +import com.yas.product.viewmodel.error.ErrorVm; import com.yas.product.viewmodel.productattribute.ProductAttributeValueGetVm; import com.yas.product.viewmodel.productattribute.ProductAttributeValuePostVm; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; - +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.BodyInserters; + +import java.util.Collections; import java.util.List; -import java.util.Objects; import java.util.Optional; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc public class ProductAttributeValueControllerTest { - ProductAttributeValueRepository productAttributeValueRepository; - ProductAttributeRepository productAttributeRepository; - ProductRepository productRepository; - ProductAttributeValueController productAttributeValueController; - UriComponentsBuilder uriComponentsBuilder; - ProductAttribute productAttribute = new ProductAttribute(); - - ProductAttributeGroup productAttributeGroup = new ProductAttributeGroup(); - ProductAttributeValue productAttributeValue; + @Autowired + private ProductAttributeGroupRepository productAttributeGroupRepository; + @Autowired + private ProductAttributeValueRepository productAttributeValueRepository; + @Autowired + private ProductAttributeRepository productAttributeRepository; + @Autowired + private ProductRepository productRepository; + + @Autowired + private WebTestClient webTestClient; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String BACK_OFFICE_URL = "/backoffice/product-attribute-value"; + private Long invalidId = 9999L; + private ProductAttributeGroup productAttributeGroup; + private ProductAttribute productAttribute; + private ProductAttributeValue productAttributeValue; + private Product product; @BeforeEach void Setup() { - productAttributeValueRepository = mock(ProductAttributeValueRepository.class); - productAttributeRepository = mock(ProductAttributeRepository.class); - productRepository = mock(ProductRepository.class); - productAttributeValueController = new ProductAttributeValueController(productAttributeValueRepository, productAttributeRepository, productRepository); - uriComponentsBuilder = mock(UriComponentsBuilder.class); - productAttributeGroup.setId(1L); + productAttributeGroup = new ProductAttributeGroup(); productAttributeGroup.setName("Computer"); - productAttribute.setId(1L); + productAttributeGroup = productAttributeGroupRepository.save(productAttributeGroup); + productAttribute = new ProductAttribute(); productAttribute.setName("Ram"); productAttribute.setProductAttributeGroup(productAttributeGroup); + productAttribute = productAttributeRepository.save(productAttribute); + productAttribute.setProductAttributeGroup(productAttributeGroup); + + product = Product.builder() + .name(String.format("product")) + .slug(String.format("slug")) + .isAllowedToOrder(true) + .isPublished(true) + .isFeatured(true) + .isVisibleIndividually(true) + .stockTrackingEnabled(true) + .build(); + product = productRepository.save(product); + productAttributeValue = new ProductAttributeValue(); - productAttributeValue.setId(1L); productAttributeValue.setValue("2 cm"); - productAttributeValue.setProduct(mock(Product.class)); + productAttributeValue.setProduct(product); productAttributeValue.setProductAttribute(productAttribute); + productAttributeValue = productAttributeValueRepository.save(productAttributeValue); } - @Test - void listProductAttributeValuesByProductId_ProductIdIsInvalid_BadRequestException() { - when(productRepository.findById(1L)).thenReturn(Optional.empty()); + @AfterEach + void tearDown() { + productAttributeValueRepository.deleteAll(); + productRepository.deleteAll(); + productAttributeRepository.deleteAll(); + productAttributeGroupRepository.deleteAll(); + } - BadRequestException exception = Assertions.assertThrows(BadRequestException.class, - () -> productAttributeValueController.listProductAttributeValuesByProductId(1L)); - assertThat(exception.getMessage(), is("Product 1 is not found")); + @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) + void listProductAttributeValuesByProductId_ProductIdIsInvalid_Return400BadRequest() { + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Product 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(BACK_OFFICE_URL + "/{productId}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) void listProductAttributeValuesByProductId_ReturnListProductAttributeValueGetVms_Success() { - Product product = mock(Product.class); - when(productRepository.findById(1L)).thenReturn(Optional.of(product)); - - List listProductAttributeValues = List.of(productAttributeValue); - when(productAttributeValueRepository.findAllByProduct(product)).thenReturn(listProductAttributeValues); - ResponseEntity> result = productAttributeValueController.listProductAttributeValuesByProductId(1L); - - assertThat(result.getStatusCode(), is(HttpStatus.OK)); - assertEquals(Objects.requireNonNull(result.getBody()).size(), listProductAttributeValues.size()); - assertEquals(result.getBody().get(0).value(), listProductAttributeValues.get(0).getValue()); - assertEquals(result.getBody().get(0).nameProductAttribute(), listProductAttributeValues.get(0).getProductAttribute().getName()); + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL + "/{productId}", product.getId()) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(ProductAttributeValueGetVm.class) + .returnResult(); + List productAttributeValueGetVms = result.getResponseBody(); + assertEquals(1, productAttributeValueGetVms.size()); + assertEquals(productAttributeValue.getValue(), productAttributeValueGetVms.get(0).value()); } @Test - void createProductAttributeValue_ProductIdIsInValid_BadRequestException() { - ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(1L, 1L, "4 cm"); - when(productRepository.findById(1L)).thenReturn(Optional.empty()); - - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - when(uriComponentsBuilder.replacePath("/product-attribute-value/{id}")).thenReturn(newUriComponentsBuilder); - - BadRequestException exception = Assertions.assertThrows(BadRequestException.class, - () -> productAttributeValueController.createProductAttributeValue(productAttributeValuePostVm, uriComponentsBuilder)); - assertThat(exception.getMessage(), is("Product 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createProductAttributeValue_ProductIdIsInValid_Return400BadRequest() { + ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(invalidId, productAttribute.getId(), "4 cm"); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Product 9999 is not found", Collections.emptyList()); + webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeValuePostVm)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void createProductAttributeValue_ProductAttributeIdIsInValid_BadRequestException() { - Product product = mock(Product.class); - ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(1L, 1L, "4 cm"); - when(productRepository.findById(1L)).thenReturn(Optional.of(product)); - when(productAttributeRepository.findById(1L)).thenReturn(Optional.empty()); - - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - when(uriComponentsBuilder.replacePath("/product-attribute-value/{id}")).thenReturn(newUriComponentsBuilder); - - BadRequestException exception = Assertions.assertThrows(BadRequestException.class, - () -> productAttributeValueController.createProductAttributeValue(productAttributeValuePostVm, uriComponentsBuilder)); - assertThat(exception.getMessage(), is("Product Attribute 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void createProductAttributeValue_ProductAttributeIdIsInValid_Return400BadRequest() { + ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(product.getId(), invalidId, "4 cm"); + ErrorVm errorVmExpected = new ErrorVm("400 BAD_REQUEST", "Bad Request", "Product Attribute 9999 is not found", Collections.emptyList()); + webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeValuePostVm)) + .exchange() + .expectStatus().isBadRequest() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) void createProductAttributeValue_ReturnProductAttributeValueVm_Success() { - Product product = mock(Product.class); - ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(1L, 1L, "4 cm"); - when(productRepository.findById(1L)).thenReturn(Optional.of(product)); - when(productAttributeRepository.findById(1L)).thenReturn(Optional.of(productAttribute)); - - var ProductAttributeValueCaptor = ArgumentCaptor.forClass(ProductAttributeValue.class); - ProductAttributeValue savedProductAttributeValue = mock(ProductAttributeValue.class); - when(savedProductAttributeValue.getProductAttribute()).thenReturn(productAttribute); - when(savedProductAttributeValue.getValue()).thenReturn(productAttributeValuePostVm.value()); - when(productAttributeValueRepository.saveAndFlush(ProductAttributeValueCaptor.capture())).thenReturn(savedProductAttributeValue); - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - UriComponents uriComponents = mock(UriComponents.class); - when(uriComponentsBuilder.replacePath("/product-attribute-value/{id}")).thenReturn(newUriComponentsBuilder); - when(newUriComponentsBuilder.buildAndExpand(savedProductAttributeValue.getId())).thenReturn(uriComponents); - - ResponseEntity result = productAttributeValueController.createProductAttributeValue(productAttributeValuePostVm - , uriComponentsBuilder); - verify(productAttributeValueRepository).saveAndFlush(ProductAttributeValueCaptor.capture()); - assertEquals(ProductAttributeValueCaptor.getValue().getValue(), productAttributeValuePostVm.value()); - assertEquals(Objects.requireNonNull(result.getBody()).value() , ProductAttributeValueCaptor.getValue().getValue()); + ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(product.getId(), productAttribute.getId(), "4 cm"); + EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeValuePostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(ProductAttributeValueGetVm.class) + .returnResult(); + ProductAttributeValueGetVm productAttributeValueGetVm = result.getResponseBody(); + assertNotNull(productAttributeValueGetVm); + assertEquals(productAttributeValuePostVm.value(), productAttributeValueGetVm.value()); } @Test - void updateProductAttributeValue_ProductAttributeValueIdIsInValid_NotFoundException(){ - ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(1L, 1L, "4 cm"); - when(productAttributeValueRepository.findById(1L)).thenReturn(Optional.empty()); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> productAttributeValueController.updateProductAttributeValue(1L, productAttributeValuePostVm)); - assertThat(exception.getMessage(), is("Product attribute value 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void updateProductAttributeValue_ProductAttributeValueIdIsInValid_Return404NotFound() { + ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(product.getId(), productAttribute.getId(), "4 cm"); + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product attribute value 9999 is not found", Collections.emptyList()); + + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeValuePostVm)) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - void updateProductAttributeValue_ProductAttributeValueIdIsValid_Success(){ - ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(1L, 1L, "4 cm"); - when(productAttributeValueRepository.findById(1L)).thenReturn(Optional.of(productAttributeValue)); - - var ProductAttributeValueCaptor = ArgumentCaptor.forClass(ProductAttributeValue.class); - ProductAttributeValue savedProductAttributeValue = mock(ProductAttributeValue.class); - when(productAttributeValueRepository.saveAndFlush(ProductAttributeValueCaptor.capture())).thenReturn(savedProductAttributeValue); - ResponseEntity result = productAttributeValueController.updateProductAttributeValue(1L,productAttributeValuePostVm); - verify(productAttributeValueRepository).saveAndFlush(ProductAttributeValueCaptor.capture()); - assertThat(result.getStatusCode(),is(HttpStatus.NO_CONTENT)); - assertEquals(ProductAttributeValueCaptor.getValue().getValue(), productAttributeValuePostVm.value()); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void updateProductAttributeValue_ProductAttributeValueIdIsValid_Success() { + ProductAttributeValuePostVm productAttributeValuePostVm = new ProductAttributeValuePostVm(product.getId(), productAttribute.getId(), "4 cm"); + + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", productAttributeValue.getId()) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productAttributeValuePostVm)) + .exchange() + .expectStatus().isNoContent(); + Optional productAttributeValueOptional = productAttributeValueRepository.findById(productAttributeValue.getId()); + assertTrue(productAttributeValueOptional.isPresent()); + assertEquals(productAttributeValuePostVm.value(), productAttributeValueOptional.get().getValue()); } + @Test - void deleteProductAttributeValueById_ProductAttributeValueIdIsInValid_Success(){ - when(productAttributeValueRepository.findById(1L)).thenReturn(Optional.empty()); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> productAttributeValueController.deleteProductAttributeValueById(1L)); - assertThat(exception.getMessage(), is("Product attribute value 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + void deleteProductAttributeValueById_ProductAttributeValueIdIsInValid_Success() { + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", productAttributeValue.getId()) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNoContent(); + Optional productAttributeValueOptional = productAttributeValueRepository.findById(productAttributeValue.getId()); + assertFalse(productAttributeValueOptional.isPresent()); } } diff --git a/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java index d8bd3744b2..542ead0b8f 100644 --- a/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java @@ -1,106 +1,147 @@ package com.yas.product.controller; -import com.yas.product.exception.NotFoundException; +import com.yas.product.ProductApplication; import com.yas.product.model.ProductOption; import com.yas.product.repository.ProductOptionRepository; +import com.yas.product.viewmodel.error.ErrorVm; import com.yas.product.viewmodel.productoption.ProductOptionGetVm; import com.yas.product.viewmodel.productoption.ProductOptionPostVm; -import com.yas.product.service.ProductOptionService; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.web.reactive.function.BodyInserters; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Optional; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc public class ProductOptionControllerTest { - private ProductOptionController productOptionController; - ProductOptionRepository productOptionRepository; - ProductOptionService productOptionService; - private Principal principal; - private UriComponentsBuilder uriComponentsBuilder; + @Autowired + private ProductOptionRepository productOptionRepository; private ProductOption productOption; + @Autowired + private WebTestClient webTestClient; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String BACK_OFFICE_URL = "/backoffice/product-options"; + private Long invalidId = 9999L; + @BeforeEach - public void setUp(){ - productOptionRepository = mock(ProductOptionRepository.class); - productOptionService = mock(ProductOptionService.class); - principal = mock(Principal.class); - uriComponentsBuilder = mock(UriComponentsBuilder.class); - productOptionController = new ProductOptionController(productOptionRepository, productOptionService); + public void setUp() { productOption = new ProductOption(); - productOption.setId(1L); - productOption.setName("hihi"); + productOption.setName("camera"); + productOption = productOptionRepository.save(productOption); + } + + @AfterEach + public void tearDown() { + productOptionRepository.deleteAll(); } @Test - public void listProductOption_ReturnListProductOption_Success(){ - List productOptions = new ArrayList<>(Arrays.asList(productOption)); - when(productOptionRepository.findAll()).thenReturn(productOptions); - ResponseEntity> result = productOptionController.listProductOption(); - assertThat(result.getStatusCode(), is(HttpStatus.OK)); - assertThat(result.getBody().size(), is(productOptions.size())); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void listProductOption_ReturnListProductOption_Success() { + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(ProductOptionGetVm.class) + .returnResult(); + List productOptionGetVms = result.getResponseBody(); + assertEquals(1, productOptionGetVms.size()); + assertEquals(productOption.getName(), productOptionGetVms.get(0).name()); } @Test - public void getProductOption_ReturnProductOptionGetVm_Success(){ - when(productOptionRepository.findById(1L)).thenReturn(Optional.of(productOption)); - ResponseEntity result = productOptionController.getProductOption(1L); - assertThat(result.getBody().name(), is("hihi")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void getProductOption_ReturnProductOptionGetVm_Success() { + EntityExchangeResult result = + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", productOption.getId()) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBody(ProductOptionGetVm.class) + .returnResult(); + ProductOptionGetVm productOptionGetVm = result.getResponseBody(); + assertNotNull(productOptionGetVm); + assertEquals(productOption.getName(), productOptionGetVm.name()); } @Test - public void getProductOption_ProductOptionIdIsInvalid_ThrowNotFoundException(){ - when(productOptionRepository.findById(2L)).thenReturn(Optional.empty()); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - ()->productOptionController.getProductOption(2L)); - assertThat(exception.getMessage(), is("Product option 2 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void getProductOption_ProductOptionIdIsInvalid_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product option 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - public void createProductOption_VaildProductOptionPostVm_Success(){ - ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("hihi"); - when(productOptionService.create(productOptionPostVm)).thenReturn(productOption); - UriComponentsBuilder newUriComponentsBuilder = mock(UriComponentsBuilder.class); - UriComponents uriComponents = mock(UriComponents.class); - when(uriComponentsBuilder.replacePath("/product-options/{id}")).thenReturn(newUriComponentsBuilder); - when(newUriComponentsBuilder.buildAndExpand(productOption.getId())).thenReturn(uriComponents); - ResponseEntity result = productOptionController.createProductOption(productOptionPostVm, principal, uriComponentsBuilder); - assertThat(result.getBody().name(), is("hihi")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void createProductOption_VaildProductOptionPostVm_Success() { + ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("speaker"); + EntityExchangeResult result = + webTestClient.post().uri(BACK_OFFICE_URL) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productOptionPostVm)) + .exchange() + .expectStatus().isCreated() + .expectBody(ProductOptionGetVm.class) + .returnResult(); + ProductOptionGetVm productOptionGetVm = result.getResponseBody(); + assertNotNull(productOptionGetVm); + assertEquals(productOptionPostVm.name(), productOptionGetVm.name()); } @Test - public void updateProductOption_ProductOptionIdIsValid_Success(){ - ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("hihi"); - when(productOptionRepository.findById(1L)).thenReturn(Optional.of(productOption)); - ResponseEntity result = productOptionController.updateProductOption(1L, productOptionPostVm, principal); - assertThat(result.getStatusCode(), is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void updateProductOption_ProductOptionIdIsValid_Success() { + ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("speaker"); + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", productOption.getId()) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productOptionPostVm)) + .exchange() + .expectStatus().isNoContent(); + Optional productOptionOptional = productOptionRepository.findById(productOption.getId()); + assertTrue(productOptionOptional.isPresent()); + assertEquals(productOptionPostVm.name(), productOptionOptional.get().getName()); } @Test - public void updateProductOption_ProductOptionIdIsInvalid_ThrowNotFoundException(){ - ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("hihi"); - when(productOptionService.update(any(), anyLong())).thenThrow(new NotFoundException("Product option 1 is not found")); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> productOptionController.updateProductOption(1L, productOptionPostVm, principal)); - assertThat(exception.getMessage(), is("Product option 1 is not found")); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void updateProductOption_ProductOptionIdIsInvalid_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product option 9999 is not found", Collections.emptyList()); + ProductOptionPostVm productOptionPostVm = new ProductOptionPostVm("speaker"); + webTestClient.put().uri(BACK_OFFICE_URL + "/{id}", invalidId) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(productOptionPostVm)) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test - public void deleteProductOption_givenProductOptionIdValid_thenSuccess(){ - when(productOptionRepository.findById(1L)).thenReturn(Optional.of(productOption)); - ResponseEntity response = productOptionController.deleteProductOption(1L); - verify(productOptionRepository).deleteById(1L); - assertThat(response.getStatusCode(), is(HttpStatus.NO_CONTENT)); + @WithMockUser(username = USERNAME, roles = {ROLE}) + public void deleteProductOption_givenProductOptionIdValid_thenSuccess() { + webTestClient.delete().uri(BACK_OFFICE_URL + "/{id}", productOption.getId()) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNoContent(); + Optional productOptionOptional = productOptionRepository.findById(productOption.getId()); + assertFalse(productOptionOptional.isPresent()); } } diff --git a/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java index a72c525024..87d30fffb0 100644 --- a/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java @@ -1,91 +1,120 @@ package com.yas.product.controller; -import com.yas.product.exception.NotFoundException; +import com.yas.product.ProductApplication; import com.yas.product.model.Product; import com.yas.product.model.ProductOption; import com.yas.product.model.ProductOptionValue; +import com.yas.product.repository.ProductOptionRepository; import com.yas.product.repository.ProductOptionValueRepository; import com.yas.product.repository.ProductRepository; +import com.yas.product.viewmodel.error.ErrorVm; import com.yas.product.viewmodel.product.ProductOptionValueGetVm; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponentsBuilder; +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.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.reactive.server.EntityExchangeResult; +import org.springframework.test.web.reactive.server.WebTestClient; +import java.util.Collections; import java.util.List; -import java.util.Objects; -import java.util.Optional; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertNotNull; +@SpringBootTest(classes = ProductApplication.class) +@AutoConfigureMockMvc class ProductOptionValueControllerTest { - ProductOptionValueRepository productOptionValueRepository; - ProductRepository productRepository; - ProductOptionValueController productOptionValueController; - UriComponentsBuilder uriComponentsBuilder; - ProductOptionValue productOptionValue = new ProductOptionValue(); - ProductOption productOption = new ProductOption(); - Product product = new Product(); + @Autowired + private ProductOptionValueRepository productOptionValueRepository; + @Autowired + private ProductRepository productRepository; + @Autowired + private ProductOptionRepository productOptionRepository; + private ProductOptionValue productOptionValue; + private ProductOption productOption; + private Product product; + @Autowired + private WebTestClient webTestClient; + private final String USERNAME = "admin"; + private final String ROLE = "ADMIN"; + private final String STORE_FRONT_URL = "/storefront/product-option-values"; + private final String BACK_OFFICE_URL = "/backoffice/product-option-values"; + private Long invalidId = 9999L; @BeforeEach void setup() { - productOptionValueRepository = mock(ProductOptionValueRepository.class); - productRepository = mock(ProductRepository.class); - uriComponentsBuilder = mock(UriComponentsBuilder.class); - productOptionValueController = new ProductOptionValueController(productOptionValueRepository, productRepository); - product = mock(Product.class); - productOption = mock(ProductOption.class); + product = Product.builder() + .name(String.format("product")) + .slug(String.format("slug")) + .isAllowedToOrder(true) + .isPublished(true) + .isFeatured(true) + .isVisibleIndividually(true) + .stockTrackingEnabled(true) + .build(); + product = productRepository.save(product); + + productOption = new ProductOption(); + productOption.setName("camera"); + productOption = productOptionRepository.save(productOption); + + productOptionValue = new ProductOptionValue(); productOptionValue.setProduct(product); productOptionValue.setProductOption(productOption); productOptionValue.setValue("red"); productOptionValue.setDisplayType("Text"); productOptionValue.setDisplayOrder(2); + productOptionValue = productOptionValueRepository.save(productOptionValue); + } + + @AfterEach + void tearDown() { + productOptionValueRepository.deleteAll(); + productOptionRepository.deleteAll(); + productRepository.deleteAll(); } @Test + @WithMockUser(username = USERNAME, roles = {ROLE}) void listProductOptionValues_ReturnListProductOptionValueGetVm_Success() { - List productOptionValues = List.of(productOptionValue); - when(productOptionValueRepository.findAll()).thenReturn(productOptionValues); - ResponseEntity> result = productOptionValueController.listProductOptionValues(); - assertThat(result.getStatusCode(), is(HttpStatus.OK)); - assertEquals(Objects.requireNonNull(result.getBody()).size(), productOptionValues.size()); - for (int i = 0; i < productOptionValues.size(); i++) { - assertEquals(result.getBody().get(i).value(), productOptionValues.get(i).getValue()); - assertEquals(result.getBody().get(i).displayType(), productOptionValues.get(i).getDisplayType()); - assertEquals(result.getBody().get(i).displayOrder(), productOptionValues.get(i).getDisplayOrder()); - } + EntityExchangeResult> result = + webTestClient.get().uri(BACK_OFFICE_URL) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(com.yas.product.viewmodel.productoption.ProductOptionValueGetVm.class) + .returnResult(); + List productOptionValueGetVms = result.getResponseBody(); + assertEquals(1, productOptionValueGetVms.size()); + assertEquals(productOptionValue.getValue(), productOptionValueGetVms.get(0).value()); } @Test - void listProductOptionValueOfProduct_ProductIdIsInvalid_ThrowNotFoundException() { - when(productRepository.findById(1L)).thenReturn(Optional.empty()); - NotFoundException exception = Assertions.assertThrows(NotFoundException.class, - () -> productOptionValueController.listProductOptionValueOfProduct(1L)); - assertThat(exception.getMessage(), Matchers.is("Product 1 is not found")); + void listProductOptionValueOfProduct_ProductIdIsInvalid_Return404NotFound() { + ErrorVm errorVmExpected = new ErrorVm("404 NOT_FOUND", "Not Found", "Product 9999 is not found", Collections.emptyList()); + webTestClient.get().uri(STORE_FRONT_URL + "/{productId}", invalidId) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isNotFound() + .expectBody(ErrorVm.class).isEqualTo(errorVmExpected); } @Test void listProductOptionValueOfProduct_ProductIdIsValid_Success() { - List productOptionValues = List.of(productOptionValue); - - when(productRepository.findById(1L)).thenReturn(Optional.of(product)); - when(productOptionValueRepository.findAllByProduct(product)).thenReturn(productOptionValues); - - ResponseEntity> result = productOptionValueController.listProductOptionValueOfProduct(1L); - - assertThat(result.getStatusCode(), is(HttpStatus.OK)); - assertEquals(Objects.requireNonNull(result.getBody()).size(), productOptionValues.size()); - for (int i = 0; i < productOptionValues.size(); i++) { - assertEquals(result.getBody().get(i).productOptionValue(), productOptionValues.get(i).getValue()); - assertEquals(result.getBody().get(i).productOptionId(), productOptionValues.get(i).getProductOption().getId()); - assertEquals(result.getBody().get(i).productOptionName(), productOptionValues.get(i).getProductOption().getName()); - } + EntityExchangeResult> result = + webTestClient.get().uri(STORE_FRONT_URL + "/{productId}", product.getId()) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus().isOk() + .expectBodyList(ProductOptionValueGetVm.class) + .returnResult(); + List productOptionValueGetVms = result.getResponseBody(); + assertEquals(1, productOptionValueGetVms.size()); + assertEquals(productOptionValue.getValue(), productOptionValueGetVms.getFirst().productOptionValue()); } } diff --git a/product/src/test/java/com/yas/product/model/ProductTest.java b/product/src/test/java/com/yas/product/model/ProductTest.java deleted file mode 100644 index 229bfc3f9e..0000000000 --- a/product/src/test/java/com/yas/product/model/ProductTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.yas.product.model; - -import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - -class ProductTest { - - @Test - void equalsVerifier() { - Product product1 = new Product(); - product1.setId(1L); - Product product2 = new Product(); - product2.setId(product1.getId()); - assertThat(product1).isEqualTo(product2); - product2.setId(2L); - assertThat(product1).isNotEqualTo(product2); - product1.setId(null); - assertThat(product1).isNotEqualTo(product2); - } -} \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/service/CategoryServiceTest.java b/product/src/test/java/com/yas/product/service/CategoryServiceTest.java index d95220a6b7..e8b27545c8 100644 --- a/product/src/test/java/com/yas/product/service/CategoryServiceTest.java +++ b/product/src/test/java/com/yas/product/service/CategoryServiceTest.java @@ -1,35 +1,47 @@ package com.yas.product.service; +import com.yas.product.ProductApplication; import com.yas.product.controller.CategoryController; import com.yas.product.model.Category; +import com.yas.product.model.ProductCategory; import com.yas.product.repository.CategoryRepository; +import com.yas.product.repository.ProductCategoryRepository; import com.yas.product.viewmodel.NoFileMediaVm; +import com.yas.product.viewmodel.category.CategoryGetDetailVm; +import com.yas.product.viewmodel.category.CategoryGetVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import java.util.List; import java.util.Optional; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +@SpringBootTest(classes = ProductApplication.class) public class CategoryServiceTest { + @Autowired private CategoryRepository categoryRepository; + @Autowired + private ProductCategoryRepository productCategoryRepository; + @MockBean private MediaService mediaService; + @Autowired private CategoryService categoryService; + private Category category; + private NoFileMediaVm noFileMediaVm; @BeforeEach void setUp() { - categoryRepository = mock(CategoryRepository.class); - mediaService = mock(MediaService.class); - categoryService = new CategoryService(categoryRepository, mediaService); - } - @Test - void getCategoryById_Success() { - Category category = new Category(); - category.setId(1L); + category = new Category(); category.setName("name"); category.setSlug("slug"); category.setDescription("description"); @@ -38,30 +50,30 @@ void getCategoryById_Success() { category.setDisplayOrder((short) 1); category.setIsPublished(true); category.setImageId(1L); - NoFileMediaVm noFileMediaVm = new NoFileMediaVm(1L, "caption", "fileName", "mediaType", "url"); + categoryRepository.save(category); + + noFileMediaVm = new NoFileMediaVm(1L, "caption", "fileName", "mediaType", "url"); + } - when(categoryRepository.findById(1L)).thenReturn(Optional.of(category)); + @AfterEach + void tearDown() { + productCategoryRepository.deleteAll(); + categoryRepository.deleteAll(); + } + + @Test + void getCategoryById_Success() { when(mediaService.getMedia(category.getImageId())).thenReturn(noFileMediaVm); - Assertions.assertNotNull(categoryService.getCategoryById(1L)); + CategoryGetDetailVm categoryGetDetailVm = categoryService.getCategoryById(category.getId()); + assertNotNull(categoryGetDetailVm); + assertEquals("name", categoryGetDetailVm.name()); } @Test void getCategories_Success() { - Category category = new Category(); - category.setId(1L); - category.setName("name"); - category.setSlug("slug"); - category.setDescription("description"); - category.setMetaKeyword("metaKeyword"); - category.setMetaDescription("metaDescription"); - category.setDisplayOrder((short) 1); - category.setIsPublished(true); - category.setImageId(1L); - List categoryList = List.of(category); - NoFileMediaVm noFileMediaVm = new NoFileMediaVm(1L, "caption", "fileName", "mediaType", "url"); - - when(categoryRepository.findAll()).thenReturn(categoryList); when(mediaService.getMedia(category.getImageId())).thenReturn(noFileMediaVm); - Assertions.assertEquals(categoryService.getCategories().size(), categoryList.size()); + Assertions.assertEquals(1, categoryService.getCategories().size()); + CategoryGetVm categoryGetVm = categoryService.getCategories().get(0); + assertEquals("name", categoryGetVm.name()); } } diff --git a/product/src/test/java/com/yas/product/service/ProductServiceTest.java b/product/src/test/java/com/yas/product/service/ProductServiceTest.java index d5cd334227..8e9237fd22 100644 --- a/product/src/test/java/com/yas/product/service/ProductServiceTest.java +++ b/product/src/test/java/com/yas/product/service/ProductServiceTest.java @@ -1,178 +1,149 @@ package com.yas.product.service; +import com.yas.product.ProductApplication; import com.yas.product.exception.NotFoundException; -import com.yas.product.model.*; +import com.yas.product.model.Brand; +import com.yas.product.model.Category; +import com.yas.product.model.Product; +import com.yas.product.model.ProductCategory; import com.yas.product.repository.*; import com.yas.product.viewmodel.NoFileMediaVm; import com.yas.product.viewmodel.product.*; -import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.web.multipart.MultipartFile; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; +@SpringBootTest(classes = ProductApplication.class) class ProductServiceTest { - ProductRepository productRepository; - MediaService mediaService; - BrandRepository brandRepository; - CategoryRepository categoryRepository; - ProductCategoryRepository productCategoryRepository; - ProductService productService; - ProductImageRepository productImageRepository; - ProductOptionRepository productOptionRepository; - ProductOptionValueRepository productOptionValueRepository; - ProductOptionCombinationRepository productOptionCombinationRepository; - ProductRelatedRepository productRelatedRepository; - - List categoryList; - Category category1; - Category category2; - List products; - List files; + @Autowired + private ProductRepository productRepository; + @Autowired + private BrandRepository brandRepository; + @Autowired + private CategoryRepository categoryRepository; + @Autowired + private ProductCategoryRepository productCategoryRepository; + @MockBean + private MediaService mediaService; + @Autowired + private ProductService productService; + + private List products; + private List categoryList; + private List productCategoryList; + private Category category1; + private Category category2; + private Brand brand1; + private Brand brand2; + private int pageNo = 0; + private int pageSize = 5; + private int totalPage = 2; private final ZonedDateTime CREATED_ON = ZonedDateTime.now(); + private NoFileMediaVm noFileMediaVm; @BeforeEach void setUp() { - productRepository = mock(ProductRepository.class); - mediaService = mock(MediaService.class); - brandRepository = mock(BrandRepository.class); - productRepository = mock(ProductRepository.class); - categoryRepository = mock(CategoryRepository.class); - productCategoryRepository = mock(ProductCategoryRepository.class); - productImageRepository = mock(ProductImageRepository.class); - productOptionRepository = mock(ProductOptionRepository.class); - productOptionValueRepository = mock(ProductOptionValueRepository.class); - productOptionCombinationRepository = mock(ProductOptionCombinationRepository.class); - productRelatedRepository = mock(ProductRelatedRepository.class); - productService = new ProductService( - productRepository, - mediaService, - brandRepository, - productCategoryRepository, - categoryRepository, - productImageRepository, - productOptionRepository, - productOptionValueRepository, - productOptionCombinationRepository, - productRelatedRepository); - category1 = new Category(1L, "category", null, "category", null, null, null, false, 1L, null, null, null); - category2 = new Category(2L, "category2", null, "category2", null, null, null, false, 1L, null, null, null); + noFileMediaVm = new NoFileMediaVm(1L, "caption", "fileName", "mediaType", "url"); + when(mediaService.getMedia(1L)).thenReturn(noFileMediaVm); + } + + private void generateTestData() { + brand1 = new Brand(); + brand1.setName("phone1"); + brand1.setSlug("brandSlug1"); + brand1.setPublished(true); + brand2 = new Brand(); + brand2.setName("phone2"); + brand2.setSlug("brandSlug2"); + brand2.setPublished(true); + brandRepository.saveAll(List.of(brand1, brand2)); + + category1 = new Category(); + category1.setName("category1"); + category1.setSlug("categorySlug1"); + category2 = new Category(); + category2.setName("category2"); + category2.setSlug("categorySlug2"); + categoryList = List.of(category1, category2); - Product product1 = Product.builder() - .id(1L) - .name("product1") - .slug("slug1") - .isAllowedToOrder(true) - .isPublished(true) - .isFeatured(true) - .isVisibleIndividually(true) - .stockTrackingEnabled(true) - .thumbnailMediaId(1L) - .productImages(new ArrayList<>() { - { - add(ProductImage.builder() - .id(1L) - .imageId(2L) - .build()); - } - }) - .taxClassId(1L) - .build(); - product1.setCreatedOn(CREATED_ON); - Product product2 = Product.builder() - .id(2L) - .name("product2") - .slug("slug2") - .isAllowedToOrder(true) - .isPublished(true) - .isFeatured(true) - .isVisibleIndividually(true) - .stockTrackingEnabled(true) - .thumbnailMediaId(1L) - .productImages(new ArrayList<>() { - { - add(ProductImage.builder() - .id(2L) - .imageId(3L) - .build()); - } - }) - .taxClassId(1L) - .build(); - product2.setCreatedOn(CREATED_ON); - - products = List.of(product1, product2); - - files = List.of(new MockMultipartFile("image.jpg", "image".getBytes())); + categoryRepository.saveAll(categoryList); + + products = new ArrayList<>(); + for (int i = 1; i <= 10; i++) { + Product product = Product.builder() + .name(String.format("product%s", i)) + .slug(String.format("slug%s", i)) + .isAllowedToOrder(true) + .isPublished(true) + .isFeatured(true) + .isVisibleIndividually(true) + .stockTrackingEnabled(true) + .thumbnailMediaId(1L) + .taxClassId(1L) + .build(); + if(i % 2 == 0) { + product.setBrand(brand2); + product.setPrice(10.0); + } else { + product.setBrand(brand1); + product.setPrice(5.0); + } + product.setCreatedOn(CREATED_ON); + products.add(product); + } + List productsDB = productRepository.saveAll(products); + + productCategoryList = new ArrayList<>(); + for (int i = 1; i <= productsDB.size(); i++) { + Product productDB = productsDB.get(i - 1); + ProductCategory productCategory = new ProductCategory(); + productCategory.setProduct(productDB); + if(i % 2 == 0) { + productCategory.setCategory(category2); + } else { + productCategory.setCategory(category1); + } + productCategoryList.add(productCategory); + } + productCategoryRepository.saveAll(productCategoryList); + } + + @AfterEach + void tearDown() { + productCategoryRepository.deleteAll(); + categoryRepository.deleteAll(); + productRepository.deleteAll(); + brandRepository.deleteAll(); } @DisplayName("Get product feature success then return list ProductThumbnailVm") @Test void getFeaturedProducts_WhenEverythingIsOkay_Success() { - //given - List productList = List.of( - Product.builder() - .id(1L) - .name("product1") - .slug("slug1") - .thumbnailMediaId(1L) - .sku("sku") - .build(), - Product.builder() - .id(2L) - .name("product2") - .sku("sku") - .slug("slug2") - .thumbnailMediaId(1L) - .build()); - String url = "sample-url"; - int totalPage = 20; - int pageNo = 0; - int pageSize = 10; - var pageCaptor = ArgumentCaptor.forClass(Pageable.class); - Page productPage = mock(Page.class); - NoFileMediaVm noFileMediaVm = mock(NoFileMediaVm.class); - - when(productRepository.getFeaturedProduct(any(Pageable.class))).thenReturn(productPage); - when(productPage.getContent()).thenReturn(productList); - when(productPage.getTotalPages()).thenReturn(totalPage); - when(mediaService.getMedia(anyLong())).thenReturn(noFileMediaVm); - when(noFileMediaVm.url()).thenReturn(url); - - //when + generateTestData(); ProductFeatureGetVm actualResponse = productService.getListFeaturedProducts(pageNo, pageSize); - - //then - verify(productRepository).getFeaturedProduct(pageCaptor.capture()); assertThat(actualResponse.totalPage()).isEqualTo(totalPage); - assertThat(actualResponse.productList().size()).isEqualTo(2); + assertThat(actualResponse.productList().size()).isEqualTo(5); + Map productMap = products.stream().collect(Collectors.toMap(Product::getSlug, product -> product)); for (int i = 0; i < actualResponse.productList().size(); i++) { - Product product = products.get(i); - assertThat(actualResponse.productList().get(i).id()).isEqualTo(product.getId()); - assertThat(actualResponse.productList().get(i).name()).isEqualTo(product.getName()); - assertThat(actualResponse.productList().get(i).slug()).isEqualTo(product.getSlug()); - assertThat(actualResponse.productList().get(i).thumbnailUrl()).isEqualTo(mediaService.getMedia(product.getThumbnailMediaId()).url()); + ProductThumbnailGetVm productThumbnailGetVm = actualResponse.productList().get(i); + Product product = productMap.get(productThumbnailGetVm.slug()); + assertEquals(product.getName(), actualResponse.productList().get(i).name()); } } @@ -180,406 +151,120 @@ void getFeaturedProducts_WhenEverythingIsOkay_Success() { @DisplayName("Get products by brand when brand is available with slug then success") @Test void getProductsByBrand_BrandSlugIsValid_Success() { - //given - String brandSlug = "iphone"; - String url = "sample-url"; - Brand existingBrand = mock(Brand.class); - NoFileMediaVm noFileMediaVm = mock(NoFileMediaVm.class); - - when(brandRepository.findBySlug(brandSlug)).thenReturn(Optional.of(existingBrand)); - when(productRepository.findAllByBrandAndIsPublishedTrue(existingBrand)).thenReturn(products); - when(mediaService.getMedia(anyLong())).thenReturn(noFileMediaVm); - when(noFileMediaVm.url()).thenReturn(url); - - //when - List actualResponse = productService.getProductsByBrand(brandSlug); - - //then - assertThat(actualResponse).hasSize(2); - for (int i = 0; i < actualResponse.size(); i++) { - Product product = products.get(i); - assertThat(actualResponse.get(i).id()).isEqualTo(product.getId()); - assertThat(actualResponse.get(i).name()).isEqualTo(product.getName()); - assertThat(actualResponse.get(i).slug()).isEqualTo(product.getSlug()); - assertThat(actualResponse.get(i).thumbnailUrl()).isEqualTo(mediaService.getMedia(product.getThumbnailMediaId()).url()); - } + generateTestData(); + List actualResponse = productService.getProductsByBrand(brand1.getSlug()); + assertEquals(5, actualResponse.size()); } @DisplayName("Get products by brand when brand is non exist then throws exception") @Test void getProductsByBrand_BrandIsNonExist_ThrowsNotFoundException() { - //given - String brandSlug = "iphone"; - when(brandRepository.findBySlug(brandSlug)).thenReturn(Optional.empty()); - - //when - NotFoundException exception = assertThrows(NotFoundException.class, () -> productService.getProductsByBrand(brandSlug)); - - //then - assertThat(exception.getMessage()).isEqualTo(String.format("Brand %s is not found", brandSlug)); + NotFoundException exception = assertThrows(NotFoundException.class, () -> productService.getProductsByBrand("brandSlug1")); + assertEquals(String.format("Brand %s is not found", "brandSlug1"), exception.getMessage()); } @Test void getProduct_whenProductIdInvalid_shouldThrowException() { - // Initial variables - Long id = 1L; - ProductPutVm productPutVm = Mockito.mock(ProductPutVm.class); - - // Stub - Mockito.when(productRepository.findById(id)).thenReturn(Optional.empty()); - - // Test - NotFoundException notFoundException = Assertions.assertThrows(NotFoundException.class, () -> - productService.updateProduct(id, productPutVm)); - - // Assert - assertThat(notFoundException.getMessage(), is(String.format("Product %s is not found", id))); + Long id = 9999L; + Exception notFoundException = assertThrows(NotFoundException.class, () -> productService.getProductById(id)); + assertEquals(String.format("Product %s is not found", id), notFoundException.getMessage()); } @Test void getProduct_whenProductIdValid_shouldSuccess() { - //Initial variables - long id = 1L; - Product product = mock(Product.class); - Brand brand = new Brand(); - brand.setId(1L); - - //Stub - Mockito.when(productRepository.findById(id)).thenReturn(Optional.of(product)); - Mockito.when(mediaService.getMedia(any())).thenReturn(new NoFileMediaVm(1L, "", "", "", "")); - Mockito.when(product.getName()).thenReturn("name"); - Mockito.when(product.getBrand()).thenReturn(brand); - - assertThat(product.getName(), is(productService.getProductById(id).name())); + generateTestData(); + List productDbList = productRepository.findAll(); + assertNotNull(productService.getProductById(productDbList.getFirst().getId())); } @Test void getListFeaturedProductsByListProductIds_whenAllProductIdsValid_shouldSuccess() { - // Initial variables - Long[] ids = {1L}; - List productIds = Arrays.asList(ids); - Product product = mock(Product.class); - - // Stub - Mockito.when(productRepository.findAllByIdIn(productIds)).thenReturn(List.of(product)); - Mockito.when(mediaService.getMedia(any())).thenReturn(new NoFileMediaVm(1L, "", "", "", "")); - - assertThat(1, is(productService.getFeaturedProductsById(productIds).size())); - } - - @Test - void getFeaturedProductsById_whenProductIdInvalid_shouldThrowException() { - // Initial variables - Long id = 1L; - ProductPutVm productPutVm = Mockito.mock(ProductPutVm.class); - - // Stub - Mockito.when(productRepository.findById(id)).thenReturn(Optional.empty()); - - // Test - NotFoundException notFoundException = Assertions.assertThrows(NotFoundException.class, () -> - productService.updateProduct(id, productPutVm)); - - // Assert - assertThat(notFoundException.getMessage(), is(String.format("Product %s is not found", id))); + generateTestData(); + List productDbList = productRepository.findAll(); + List ids = productDbList.stream().map(Product::getId).collect(Collectors.toList()); + assertEquals(10, productService.getFeaturedProductsById(ids).size()); } @Test void getProductsWithFilter_WhenFilterByBrandNameAndProductName_ThenSuccess() { - //given - Page productPage = mock(Page.class); - List productListVmList = List.of( - new ProductListVm(products.get(0).getId(), products.get(0).getName(), products.get(0).getSlug(), - true, true, true, true, CREATED_ON, products.get(0).getTaxClassId()), - new ProductListVm(products.get(1).getId(), products.get(1).getName(), products.get(1).getSlug(), - true, true, true, true, CREATED_ON, products.get(0).getTaxClassId()) - ); - int pageNo = 1; - int pageSize = 10; - int totalElement = 20; - int totalPages = 4; - String productName = " Xiaomi "; - String brandName = " Xiaomi "; - var pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - var productNameCaptor = ArgumentCaptor.forClass(String.class); - var brandNameCaptor = ArgumentCaptor.forClass(String.class); - - when(productRepository.getProductsWithFilter(anyString(), anyString(), any(Pageable.class))).thenReturn(productPage); - when(productPage.getContent()).thenReturn(products); - when(productPage.getNumber()).thenReturn(pageNo); - when(productPage.getTotalElements()).thenReturn((long) totalElement); - when(productPage.getTotalPages()).thenReturn(totalPages); - when(productPage.isLast()).thenReturn(false); - - //when - ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, productName, brandName); - - //then - verify(productRepository).getProductsWithFilter( - productNameCaptor.capture(), - brandNameCaptor.capture(), - pageableCaptor.capture()); - assertThat(productNameCaptor.getValue()).contains(productName.trim().toLowerCase()); - assertThat(brandNameCaptor.getValue()).isEqualTo(brandName.trim()); - assertThat(pageableCaptor.getValue()).isEqualTo(PageRequest.of(pageNo, pageSize)); - - assertThat(actualResponse.productContent()).isEqualTo(productListVmList); - assertThat(actualResponse.pageNo()).isEqualTo(productPage.getNumber()); - assertThat(actualResponse.pageSize()).isEqualTo(productPage.getSize()); - assertThat(actualResponse.totalElements()).isEqualTo(productPage.getTotalElements()); - assertThat(actualResponse.totalPages()).isEqualTo(productPage.getTotalPages()); - assertThat(actualResponse.isLast()).isEqualTo(productPage.isLast()); + generateTestData(); + ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, "product1", brand1.getName()); + assertEquals(1, actualResponse.productContent().size()); } @Test void getProductsWithFilter_WhenFilterByBrandName_ThenSuccess() { - //given - Page productPage = mock(Page.class); - List productListVmList = List.of( - new ProductListVm(products.get(0).getId(), products.get(0).getName(), products.get(0).getSlug(), - products.get(0).isAllowedToOrder(), products.get(0).isPublished(), - products.get(0).isFeatured(), products.get(0).isVisibleIndividually(), products.get(0).getCreatedOn(), products.get(0).getTaxClassId()), - new ProductListVm(products.get(1).getId(), products.get(1).getName(), products.get(1).getSlug(), - products.get(0).isAllowedToOrder(), products.get(0).isPublished(), - products.get(0).isFeatured(), products.get(0).isVisibleIndividually(), products.get(0).getCreatedOn(), products.get(0).getTaxClassId()) - ); - int pageNo = 1; - int pageSize = 10; - int totalElement = 20; - int totalPages = 4; - String productName = " "; - String brandName = " Xiaomi "; - var pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - var brandNameCaptor = ArgumentCaptor.forClass(String.class); - var productNameCaptor = ArgumentCaptor.forClass(String.class); - - when(productRepository.getProductsWithFilter(productNameCaptor.capture(), brandNameCaptor.capture(), pageableCaptor.capture())).thenReturn(productPage); - when(productPage.getContent()).thenReturn(products); - when(productPage.getNumber()).thenReturn(pageNo); - when(productPage.getTotalElements()).thenReturn((long) totalElement); - when(productPage.getTotalPages()).thenReturn(totalPages); - when(productPage.isLast()).thenReturn(false); - - //when - ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, productName, brandName); - - //then - assertThat(brandNameCaptor.getValue()).isEqualTo(brandName.trim()); - assertThat(pageableCaptor.getValue()).isEqualTo(PageRequest.of(pageNo, pageSize)); - assertThat(actualResponse.productContent()).isEqualTo(productListVmList); - assertThat(actualResponse.pageNo()).isEqualTo(productPage.getNumber()); - assertThat(actualResponse.pageSize()).isEqualTo(productPage.getSize()); - assertThat(actualResponse.totalElements()).isEqualTo(productPage.getTotalElements()); - assertThat(actualResponse.totalPages()).isEqualTo(productPage.getTotalPages()); - assertThat(actualResponse.isLast()).isEqualTo(productPage.isLast()); + generateTestData(); + ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, "", brand1.getName()); + assertEquals(5, actualResponse.productContent().size()); } @Test void getProductsWithFilter_WhenFilterByProductName_ThenSuccess() { - //given - Page productPage = mock(Page.class); - List productListVmList = List.of( - new ProductListVm(products.get(0).getId(), products.get(0).getName(), products.get(0).getSlug(), - products.get(0).isAllowedToOrder(), products.get(0).isPublished(), - products.get(0).isFeatured(), products.get(0).isVisibleIndividually(), products.get(0).getCreatedOn(), products.get(0).getTaxClassId()), - new ProductListVm(products.get(1).getId(), products.get(1).getName(), products.get(1).getSlug(), - products.get(0).isAllowedToOrder(), products.get(0).isPublished(), - products.get(0).isFeatured(), products.get(0).isVisibleIndividually(), products.get(0).getCreatedOn(), products.get(0).getTaxClassId()) - ); - int pageNo = 1; - int pageSize = 10; - int totalElement = 20; - int totalPages = 4; - String productName = " Xiaomi 12"; - String brandName = " "; - var pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - var productNameCaptor = ArgumentCaptor.forClass(String.class); - var brandNameCaptor = ArgumentCaptor.forClass(String.class); - - when(productRepository.getProductsWithFilter(productNameCaptor.capture(), brandNameCaptor.capture(), pageableCaptor.capture())).thenReturn(productPage); - when(productPage.getContent()).thenReturn(products); - when(productPage.getNumber()).thenReturn(pageNo); - when(productPage.getTotalElements()).thenReturn((long) totalElement); - when(productPage.getTotalPages()).thenReturn(totalPages); - when(productPage.isLast()).thenReturn(false); - - //when - ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, productName, brandName); - - //then - assertThat(productNameCaptor.getValue()).isEqualTo(productName.trim().toLowerCase()); - assertThat(pageableCaptor.getValue()).isEqualTo(PageRequest.of(pageNo, pageSize)); - assertThat(actualResponse.productContent()).isEqualTo(productListVmList); - assertThat(actualResponse.pageNo()).isEqualTo(productPage.getNumber()); - assertThat(actualResponse.pageSize()).isEqualTo(productPage.getSize()); - assertThat(actualResponse.totalElements()).isEqualTo(productPage.getTotalElements()); - assertThat(actualResponse.totalPages()).isEqualTo(productPage.getTotalPages()); - assertThat(actualResponse.isLast()).isEqualTo(productPage.isLast()); + generateTestData(); + ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, "product9", ""); + assertEquals(1, actualResponse.productContent().size()); } @Test void getProductsWithFilter_whenFindAll_thenSuccess() { - // Create a mock ProductRepository and mock Page object - Page productPage = mock(Page.class); - - // Set up mock behavior for ProductRepository and Page - when(productRepository.getProductsWithFilter(anyString(), anyString(), any(Pageable.class))).thenReturn(productPage); - when(productPage.getContent()).thenReturn(products); - when(productPage.getNumber()).thenReturn(0); - when(productPage.getSize()).thenReturn(2); - when(productPage.getTotalElements()).thenReturn(2L); - when(productPage.getTotalPages()).thenReturn(1); - when(productPage.isLast()).thenReturn(true); - - // Create an instance of the class under test and call the method - ProductListGetVm result = productService.getProductsWithFilter(0, 2, "product", "Brand"); - - // Verify that the mock objects were called with the expected arguments - verify(productRepository).getProductsWithFilter("product", "Brand", PageRequest.of(0, 2)); - - // Verify that the result has the expected values - assertEquals(2, result.productContent().size()); - assertEquals(0, result.pageNo()); - assertEquals(2, result.pageSize()); - assertEquals(2, result.totalElements()); - assertEquals(1, result.totalPages()); - assertTrue(result.isLast()); + generateTestData(); + ProductListGetVm actualResponse = productService.getProductsWithFilter(pageNo, pageSize, "product", brand2.getName()); + assertEquals(5, actualResponse.productContent().size()); } @Test void getProductsFromCategory_WhenFindAllByCategory_ThenSuccess() { - //given - Page productCategoryPage = mock(Page.class); - List productCategoryList = List.of( - new ProductCategory(1L, products.get(0), null, 1, true), - new ProductCategory(2L, products.get(1), null, 2, true) - ); - String categorySlug = "laptop-macbook"; - String url = "sample-url"; - var existingCategory = mock(Category.class); - NoFileMediaVm noFileMediaVm = mock(NoFileMediaVm.class); - int pageNo = 1; - int pageSize = 10; - int totalElement = 20; - int totalPages = 4; - var pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - when(categoryRepository.findBySlug(categorySlug)).thenReturn(Optional.of(existingCategory)); - when(productCategoryRepository.findAllByCategory(pageableCaptor.capture(), eq(existingCategory))).thenReturn(productCategoryPage); - - when(productCategoryPage.getContent()).thenReturn(productCategoryList); - when(productCategoryPage.getNumber()).thenReturn(pageNo); - when(productCategoryPage.getTotalElements()).thenReturn((long) totalElement); - when(productCategoryPage.getTotalPages()).thenReturn(totalPages); - when(productCategoryPage.isLast()).thenReturn(false); - when(mediaService.getMedia(anyLong())).thenReturn(noFileMediaVm); - when(noFileMediaVm.url()).thenReturn(url); - - //when - ProductListGetFromCategoryVm actualResponse = productService.getProductsFromCategory(pageNo, pageSize, categorySlug); - - //then - assertThat(actualResponse.productContent()).hasSize(2); - assertThat(actualResponse.pageNo()).isEqualTo(productCategoryPage.getNumber()); - assertThat(actualResponse.pageSize()).isEqualTo(productCategoryPage.getSize()); - assertThat(actualResponse.totalElements()).isEqualTo(productCategoryPage.getTotalElements()); - assertThat(actualResponse.totalPages()).isEqualTo(productCategoryPage.getTotalPages()); - assertThat(actualResponse.isLast()).isEqualTo(productCategoryPage.isLast()); + generateTestData(); + ProductListGetFromCategoryVm actualResponse = productService.getProductsFromCategory(pageNo, pageSize, "categorySlug1"); + assertEquals(5, actualResponse.productContent().size()); } @Test void getProductsFromCategory_CategoryIsNonExist_ThrowsNotFoundException() { - //given + generateTestData(); String categorySlug = "laptop-macbook"; - when(categoryRepository.findBySlug(categorySlug)).thenReturn(Optional.empty()); - int pageNo = 1; - int pageSize = 10; - - //when NotFoundException exception = assertThrows(NotFoundException.class, () -> productService.getProductsFromCategory(pageNo, pageSize, categorySlug)); - - //then assertThat(exception.getMessage()).isEqualTo(String.format("Category %s is not found", categorySlug)); } @Test void deleteProduct_givenProductIdValid_thenSuccess() { - // Initial variables - Long productId = 1L; - Product product = new Product(); - product.setId(productId); - when(productRepository.findById(productId)).thenReturn(Optional.of(product)); - - // Call method under test - productService.deleteProduct(productId); - - // Verifying that the repository was called with expected parameters - ArgumentCaptor idCaptor = ArgumentCaptor.forClass(Long.class); - verify(productRepository).findById(idCaptor.capture()); - Long capturedId = idCaptor.getValue(); - assertEquals(productId, capturedId); - - verify(productRepository).save(product); - assertFalse(product.isPublished()); + generateTestData(); + Long id = productRepository.findAll().getFirst().getId(); + productService.deleteProduct(id); + Optional result = productRepository.findById(id); + // Soft delete, set published to false + assertTrue(result.isPresent()); + assertFalse(result.get().isPublished()); + } @Test - void deleteProductAttribute_givenProductAttributeIdInvalid_thenThrowNotFoundException() { - Long productId = 1L; - when(productRepository.findById(productId)).thenReturn(Optional.empty()); + void deleteProduct_givenProductIdInvalid_thenThrowNotFoundException() { + Long productId = 99999L; assertThrows(NotFoundException.class, () -> productService.deleteProduct(productId)); } @Test void getProductsByMultiQuery_WhenFilterByBrandNameAndProductName_ThenSuccess() { - // Given - int pageNo = 0; - int pageSize = 9; + generateTestData(); Double startPrice = 1.0; Double endPrice = 10.0; - String productName = "product1"; - String categorySlug = "category1"; - String url = "sample-url"; - - Page productPage = new PageImpl<>(products, PageRequest.of(0, 2), 2); - NoFileMediaVm noFileMediaVm = mock(NoFileMediaVm.class); - - when(productRepository.findByProductNameAndCategorySlugAndPriceBetween( - anyString(), anyString(), anyDouble(), anyDouble(), any(Pageable.class))).thenReturn(productPage); - when(mediaService.getMedia(anyLong())).thenReturn(new NoFileMediaVm(null, "", "", "", url)); - - ArgumentCaptor pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - ArgumentCaptor productNameCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor categorySlugCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor startPriceCaptor = ArgumentCaptor.forClass(Double.class); - ArgumentCaptor endPriceCaptor = ArgumentCaptor.forClass(Double.class); - - // Call method under test - ProductsGetVm result = productService.getProductsByMultiQuery(pageNo, pageSize, productName, categorySlug, startPrice, endPrice); - - // Verifying that the repository was called with expected parameters - verify(productRepository).findByProductNameAndCategorySlugAndPriceBetween( - productNameCaptor.capture(), categorySlugCaptor.capture(), startPriceCaptor.capture(), - endPriceCaptor.capture(), pageableCaptor.capture()); - assertThat(pageableCaptor.getValue()).isEqualTo(PageRequest.of(pageNo, pageSize)); - assertThat(productNameCaptor.getValue()).contains(productName.trim().toLowerCase()); - assertEquals("product1", productNameCaptor.getValue()); - assertEquals("category1", categorySlugCaptor.getValue()); + String productName = "product2"; + ProductsGetVm result = productService.getProductsByMultiQuery(pageNo, pageSize, productName, category2.getSlug(), startPrice, endPrice); // Assert result - assertEquals(2, result.productContent().size()); - assertEquals(0, result.pageNo()); - assertEquals(2, result.pageSize()); - assertEquals(2, result.totalElements()); + assertEquals(1, result.productContent().size()); + ProductThumbnailGetVm thumbnailGetVm = result.productContent().getFirst(); + assertEquals("product2", thumbnailGetVm.name()); + assertEquals("slug2", thumbnailGetVm.slug()); + assertEquals(10.0, thumbnailGetVm.price()); + assertEquals(pageNo, result.pageNo()); + assertEquals(pageSize, result.pageSize()); + assertEquals(1, result.totalElements()); assertEquals(1, result.totalPages()); assertTrue(result.isLast()); - assertThat(result.pageNo()).isEqualTo(productPage.getNumber()); - assertThat(result.pageSize()).isEqualTo(productPage.getSize()); - assertThat(result.totalElements()).isEqualTo(productPage.getTotalElements()); - assertThat(result.totalPages()).isEqualTo(productPage.getTotalPages()); - assertThat(result.isLast()).isEqualTo(productPage.isLast()); - - when(mediaService.getMedia(anyLong())).thenReturn(noFileMediaVm); - when(noFileMediaVm.url()).thenReturn(url); } } \ No newline at end of file diff --git a/product/src/test/java/com/yas/product/service/ProductTemplateServiceTest.java b/product/src/test/java/com/yas/product/service/ProductTemplateServiceTest.java index f1cc088f93..d0e789c03c 100644 --- a/product/src/test/java/com/yas/product/service/ProductTemplateServiceTest.java +++ b/product/src/test/java/com/yas/product/service/ProductTemplateServiceTest.java @@ -1,38 +1,51 @@ package com.yas.product.service; +import com.yas.product.ProductApplication; import com.yas.product.exception.BadRequestException; import com.yas.product.exception.DuplicatedException; import com.yas.product.exception.NotFoundException; import com.yas.product.model.attribute.ProductAttribute; import com.yas.product.model.attribute.ProductAttributeTemplate; import com.yas.product.model.attribute.ProductTemplate; -import com.yas.product.repository.*; +import com.yas.product.repository.ProductAttributeGroupRepository; +import com.yas.product.repository.ProductAttributeRepository; +import com.yas.product.repository.ProductAttributeTemplateRepository; +import com.yas.product.repository.ProductTemplateRepository; import com.yas.product.utils.Constants; -import com.yas.product.viewmodel.producttemplate.*; +import com.yas.product.viewmodel.producttemplate.ProductAttributeTemplatePostVm; +import com.yas.product.viewmodel.producttemplate.ProductTemplateListGetVm; +import com.yas.product.viewmodel.producttemplate.ProductTemplatePostVm; +import com.yas.product.viewmodel.producttemplate.ProductTemplateVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; -import java.util.*; -import java.util.stream.Stream; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; +@SpringBootTest(classes = ProductApplication.class) class ProductTemplateServiceTest { - private ProductTemplateService productTemplateService; - private ProductAttributeRepository productAttributeRepository; - private ProductAttributeTemplateRepository productAttributeTemplateRepository; - private ProductAttributeGroupRepository productAttributeGroupRepository ; - private ProductTemplateRepository productTemplateRepository; + @Autowired + private ProductTemplateService productTemplateService; + @Autowired + private ProductAttributeRepository productAttributeRepository; + @Autowired + private ProductAttributeTemplateRepository productAttributeTemplateRepository; + @Autowired + private ProductAttributeGroupRepository productAttributeGroupRepository; + @Autowired + private ProductTemplateRepository productTemplateRepository; ProductAttribute productAttribute1; ProductAttribute productAttribute2; - List productTemplates; + List productAttributes; + ProductAttributeTemplate productAttributeTemplate1; ProductAttributeTemplate productAttributeTemplate2; ProductTemplate productTemplate1; @@ -40,29 +53,17 @@ class ProductTemplateServiceTest { @BeforeEach void setUp(){ - productTemplateService =mock(ProductTemplateService.class); - productAttributeRepository = mock(ProductAttributeRepository.class); - productAttributeTemplateRepository = mock(ProductAttributeTemplateRepository.class); - productAttributeGroupRepository = mock(ProductAttributeGroupRepository.class); - productTemplateRepository= mock(ProductTemplateRepository.class); - productTemplateService = new ProductTemplateService( - productAttributeRepository, - productAttributeTemplateRepository, - productAttributeGroupRepository, - productTemplateRepository - ); - productAttribute1 = new ProductAttribute(1L,"productAttribute1",null,null,null); - productAttribute2 = new ProductAttribute(2L,"productAttribute2",null,null,null); - productTemplate1 = ProductTemplate.builder() - .id(1L) - .name("productTemplate1") - .productAttributeTemplates(null) - .build(); - productTemplate2 = ProductTemplate.builder() - .id(2L) - .name("productTemplate2") - .productAttributeTemplates(null) - .build(); + productAttribute1 = ProductAttribute.builder().name("productAttribute1").build(); + productAttribute1 = productAttributeRepository.save(productAttribute1); + productAttribute2 = ProductAttribute.builder().name("productAttribute2").build(); + productAttribute2 = productAttributeRepository.save(productAttribute2); + productAttributes = List.of(productAttribute1, productAttribute2); + + productTemplate1 = ProductTemplate.builder().name("productTemplate1").build(); + productTemplate1 = productTemplateRepository.save(productTemplate1); + productTemplate2 = ProductTemplate.builder().name("productTemplate2").build(); + productTemplate2 = productTemplateRepository.save(productTemplate2); + productAttributeTemplate1 = ProductAttributeTemplate.builder() .productTemplate(productTemplate1) .productAttribute(productAttribute1) @@ -71,177 +72,79 @@ void setUp(){ .productTemplate(productTemplate2) .productAttribute(productAttribute2) .build(); - productTemplates = List.of(productTemplate1, productTemplate1); + productAttributeTemplateRepository.saveAll( + List.of(productAttributeTemplate1, productAttributeTemplate2)); + } + + @AfterEach + void tearDown(){ + productAttributeTemplateRepository.deleteAll(); + productAttributeRepository.deleteAll(); + productTemplateRepository.deleteAll(); } @Test void getPageableProductTemplate_WhenGetPageable_thenSuccess(){ - Page productTemplatePage = mock(Page.class); - List productTemplateListGetVms = new ArrayList<>(); - productTemplateListGetVms.add(new ProductTemplateGetVm(productTemplates.get(0).getId(), productTemplates.get(0).getName())); - productTemplateListGetVms.add(new ProductTemplateGetVm(productTemplates.get(1).getId(), productTemplates.get(1).getName())); - int pageNo = 1; + int pageNo = 0; int pageSize = 10; - int totalElement = 20; + int totalElement = 2; int totalPages = 1; - var pageableCaptor = ArgumentCaptor.forClass(Pageable.class); - when(productTemplateRepository.findAll(any(Pageable.class))).thenReturn(productTemplatePage); - when(productTemplatePage.getContent()).thenReturn(productTemplates); - when(productTemplatePage.getNumber()).thenReturn(pageNo); - when(productTemplatePage.getTotalElements()).thenReturn((long) totalElement); - when(productTemplatePage.getTotalPages()).thenReturn(totalPages); - when(productTemplatePage.isLast()).thenReturn(false); - //when ProductTemplateListGetVm actualResponse = productTemplateService.getPageableProductTemplate(pageNo,pageSize); - //then - verify(productTemplateRepository).findAll(pageableCaptor.capture()); - assertThat(actualResponse.isLast()).isEqualTo(productTemplatePage.isLast()); - assertThat(actualResponse.totalPages()).isEqualTo(productTemplatePage.getTotalPages()); - assertThat(actualResponse.pageNo()).isEqualTo(productTemplatePage.getNumber()); - assertThat(actualResponse.pageSize()).isEqualTo(productTemplatePage.getSize()); - assertThat(actualResponse.productTemplateVms()).isEqualTo(productTemplateListGetVms); + assertEquals(true, actualResponse.isLast()); + assertEquals(totalPages, actualResponse.totalPages()); + assertEquals(pageNo, actualResponse.pageNo()); + assertEquals(pageSize, actualResponse.pageSize()); + assertEquals(totalElement, actualResponse.productTemplateVms().size()); + } @Test void getProductTemplate_WhenIdProductTemplateNotExit_ThrowsNotFoundException() { - when(productTemplateRepository.findById(1L)).thenReturn(Optional.empty()); - //when - NotFoundException exception = assertThrows(NotFoundException.class, () -> productTemplateService.getProductTemplate(1L)); - //then - assertThat(exception.getMessage()).isEqualTo(Constants.ERROR_CODE.PRODUCT_TEMPlATE_IS_NOT_FOUND, 1L); + Long invalidId = 9999L; + NotFoundException exception = assertThrows(NotFoundException.class, () -> productTemplateService.getProductTemplate(invalidId)); + assertEquals(Constants.ERROR_CODE.PRODUCT_TEMPlATE_IS_NOT_FOUND, exception.getMessage()); } @Test void getProductTemplate_WhenIdProductTemplateValid_thenSuccess(){ - when(productTemplateRepository.findById(1L)).thenReturn(Optional.of(productTemplates.get(0))); - when(productAttributeTemplateRepository.findAllByProductTemplateId(1L)) - .thenReturn(List.of(productAttributeTemplate1)); - //when - ProductTemplateVm actualResponse = productTemplateService.getProductTemplate(1L); - - assertThat(actualResponse.id()).isEqualTo(1L); - assertThat(actualResponse.name()).isEqualTo(productTemplates.get(0).getName()); - assertThat(actualResponse.productAttributeTemplates()).isEqualTo(Stream.of(productAttributeTemplate1).map(ProductAttributeTemplateGetVm::fromModel).toList()); + ProductTemplate productTemplateDB = productTemplateRepository.findAll().getFirst(); + ProductTemplateVm actualResponse = productTemplateService.getProductTemplate(productTemplateDB.getId()); + assertEquals(productTemplateDB.getId(), actualResponse.id()); + assertEquals(productTemplateDB.getName(), actualResponse.name()); + assertEquals(1, actualResponse.productAttributeTemplates().size()); } @Test void saveProductTemplate_WhenDuplicateName_ThenThrowDuplicatedException(){ ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate1",null); - - when(productTemplateRepository.findExistedName(productTemplatePostVm.name(),null)).thenReturn(productTemplate1); - //when DuplicatedException exception = assertThrows(DuplicatedException.class, () -> productTemplateService.saveProductTemplate(productTemplatePostVm)); - //then - assertThat(exception.getMessage()).isEqualTo("Request name productTemplate1 is already existed"); + assertEquals("Request name productTemplate1 is already existed", exception.getMessage()); } @Test - void saveProductTemplate_WhenProductAttributesNull_ThenThrowBadRequestException(){ + void saveProductTemplate_WhenProductAttributesNotFound_ThenThrowBadRequestException(){ List listProductAttTemplates = new ArrayList<>(); - listProductAttTemplates.add(new ProductAttributeTemplatePostVm(1L,0)); - ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate1",listProductAttTemplates); - when(productAttributeRepository.findAllById(listProductAttTemplates.stream().map(ProductAttributeTemplatePostVm::ProductAttributeId).toList())).thenReturn(new ArrayList<>()); - //when + listProductAttTemplates.add(new ProductAttributeTemplatePostVm(9999L,0)); + ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate3",listProductAttTemplates); BadRequestException exception = assertThrows(BadRequestException.class, () -> productTemplateService.saveProductTemplate(productTemplatePostVm)); - //then - assertThat(exception.getMessage()).isEqualTo(Constants.ERROR_CODE.PRODUCT_ATTRIBUTE_NOT_FOUND); - } - - @Test - void saveProductTemplate_WhenProductAttributesMissId_ThenThrowBadRequestException(){ - List listProductAttTemplates = Arrays.asList( - new ProductAttributeTemplatePostVm(1L,0), - new ProductAttributeTemplatePostVm(5L,0) - ); - ProductTemplatePostVm productTemplatePostVm2 = new ProductTemplatePostVm("productTemplate2",listProductAttTemplates); - List idAttributes = new ArrayList<>(listProductAttTemplates.stream().map(ProductAttributeTemplatePostVm::ProductAttributeId).toList()); - List productAttributes = Collections.singletonList( - productAttribute1 - ); - - //when - when(productAttributeRepository.findById(listProductAttTemplates.get(0).ProductAttributeId())).thenReturn(Optional.ofNullable(productAttribute1)); - when(productAttributeRepository.findById(listProductAttTemplates.get(1).ProductAttributeId())).thenReturn(Optional.empty()); - when(productAttributeRepository.findAllById(idAttributes)).thenReturn(notNull()); - when(productAttributeRepository.findAllById(idAttributes)).thenReturn(productAttributes); - - //then - idAttributes.removeAll(productAttributes.stream().map(ProductAttribute::getId).toList()); - BadRequestException exception = assertThrows(BadRequestException.class, () -> productTemplateService.saveProductTemplate(productTemplatePostVm2)); - assertThat(exception.getMessage()).isEqualTo(Constants.ERROR_CODE.PRODUCT_ATTRIBUTE_NOT_FOUND); } @Test void saveProductTemplate_WhenProductTemplatePostVm_ThenSuccess(){ - List attributeTemplateList = new ArrayList<>(); - List listProductAttTemplates = Arrays.asList( - new ProductAttributeTemplatePostVm(1L,0), - new ProductAttributeTemplatePostVm(2L,0) - ); - ProductTemplate productTemplate = new ProductTemplate(); - ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate1",listProductAttTemplates); - List idAttributes = new ArrayList<>(listProductAttTemplates.stream().map(ProductAttributeTemplatePostVm::ProductAttributeId).toList()); - List productAttributes = Arrays.asList( - productAttribute1, - productAttribute2 - ); - - productTemplate.setName(productTemplatePostVm.name()); - - //when - when(productAttributeRepository.findAllById(idAttributes)).thenReturn(productAttributes); - when(productAttributeRepository.findAllById(idAttributes)).thenReturn(notNull()); - when(productAttributeRepository.findAllById(idAttributes)).thenReturn(productAttributes); - assertFalse(productAttributeRepository.findAllById(idAttributes).isEmpty()); - assertFalse(productAttributeRepository.findAllById(idAttributes).size() < productTemplatePostVm.ProductAttributeTemplates().size()); - - Map mockProductAttributeMap = mock(Map.class); - - when(mockProductAttributeMap.get(1L)).thenReturn(productAttributes.get(0)); - when(mockProductAttributeMap.get(2L)).thenReturn(productAttributes.get(1)); - - for (ProductAttributeTemplatePostVm attributeTemplatePostVm : listProductAttTemplates) { - attributeTemplateList.add(ProductAttributeTemplate - .builder() - .productAttribute(mockProductAttributeMap.get(attributeTemplatePostVm.ProductAttributeId())) - .productTemplate(productTemplate) - .displayOrder(attributeTemplatePostVm.displayOrder()) - .build() - ); - } - productAttributeTemplate1 = ProductAttributeTemplate.builder() - .id(1L) - .productTemplate(productTemplate) - .productAttribute(productAttribute1) - .build(); - productAttributeTemplate2 = ProductAttributeTemplate.builder() - .id(2L) - .productTemplate(productTemplate) - .productAttribute(productAttribute2) - .build(); - List productAttributeTemplates = List.of(productAttributeTemplate1, productAttributeTemplate2); - - ProductTemplate mainSavedProductTemplate = ProductTemplate.builder() - .id(1L) - .productAttributeTemplates(productAttributeTemplates) - .name(productTemplatePostVm.name()) - .build(); - - when(productTemplateRepository.save(productTemplate)).thenReturn(mainSavedProductTemplate); - when(productAttributeTemplateRepository.saveAllAndFlush(attributeTemplateList)).thenReturn(productAttributeTemplates); - - assertEquals("productAttribute1", attributeTemplateList.get(0).getProductAttribute().getName()); - assertEquals(0, attributeTemplateList.get(0).getDisplayOrder()); - assertEquals(mainSavedProductTemplate.getName(), productTemplate.getName()); + ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate3", + List.of(new ProductAttributeTemplatePostVm(productAttribute1.getId(), 0))); + ProductTemplateVm productTemplateVmDB = productTemplateService.saveProductTemplate(productTemplatePostVm); + Optional productTemplate = productTemplateRepository.findById(productTemplateVmDB.id()); + assertTrue(productTemplate.isPresent()); + assertEquals(productTemplatePostVm.name(), productTemplate.get().getName()); } + @Test void updateProductTemplate_WhenIdProductTemplateNotExist_ThenThrowNotFoundException(){ - when(productTemplateRepository.findById(1L)).thenReturn(Optional.empty()); - ProductTemplatePostVm productTemplatePostVm = mock(ProductTemplatePostVm.class); - //when - NotFoundException exception = assertThrows(NotFoundException.class, () -> productTemplateService.updateProductTemplate(1L,productTemplatePostVm)); - //then - assertThat(exception.getMessage()).isEqualTo(Constants.ERROR_CODE.PRODUCT_TEMPlATE_IS_NOT_FOUND, 1L); + ProductTemplatePostVm productTemplatePostVm = new ProductTemplatePostVm("productTemplate2", + List.of(new ProductAttributeTemplatePostVm(productAttribute1.getId(), 0))); + NotFoundException exception = assertThrows(NotFoundException.class, () -> productTemplateService.updateProductTemplate(9999L, productTemplatePostVm)); + assertEquals(Constants.ERROR_CODE.PRODUCT_TEMPlATE_IS_NOT_FOUND, exception.getMessage()); } } diff --git a/product/src/test/resources/application.properties b/product/src/test/resources/application.properties index 118d5441f2..8fef95fcb4 100644 --- a/product/src/test/resources/application.properties +++ b/product/src/test/resources/application.properties @@ -1,6 +1,8 @@ -# Setting Spring context path & port -server.servlet.context-path=/v1 server.port=8080 +server.servlet.context-path=/product + +# Setting Spring profile +spring.profiles.active=test spring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=VALUE spring.datasource.driverClassName=org.h2.Driver @@ -9,12 +11,8 @@ spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false -# Setting Spring profile -spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true - -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.product \ No newline at end of file +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test \ No newline at end of file diff --git a/promotion/pom.xml b/promotion/pom.xml index 7894616e15..fcf4a209a3 100644 --- a/promotion/pom.xml +++ b/promotion/pom.xml @@ -87,6 +87,11 @@ org.liquibase liquibase-core + + com.h2database + h2 + test + net.logstash.logback diff --git a/promotion/src/main/java/com/yas/promotion/repository/PromotionRepository.java b/promotion/src/main/java/com/yas/promotion/repository/PromotionRepository.java index 5fdb09bab3..21af9bf0fc 100644 --- a/promotion/src/main/java/com/yas/promotion/repository/PromotionRepository.java +++ b/promotion/src/main/java/com/yas/promotion/repository/PromotionRepository.java @@ -16,8 +16,8 @@ public interface PromotionRepository extends JpaRepository { Optional findBySlugAndIsActiveTrue(String slug); @Query("SELECT p FROM Promotion p " + - "WHERE p.name LIKE %:name% " + - "AND p.couponCode LIKE %:couponCode% " + + "WHERE LOWER(p.name) LIKE LOWER(CONCAT('%',:name,'%')) " + + "AND LOWER(p.couponCode) LIKE LOWER(CONCAT('%',:couponCode,'%')) " + "AND p.startDate >= :startDate " + "AND p.endDate <= :endDate") Page findPromotions(@Param("name") String name, diff --git a/promotion/src/main/java/com/yas/promotion/service/PromotionService.java b/promotion/src/main/java/com/yas/promotion/service/PromotionService.java index 8141dbc5c4..f24bedd47e 100644 --- a/promotion/src/main/java/com/yas/promotion/service/PromotionService.java +++ b/promotion/src/main/java/com/yas/promotion/service/PromotionService.java @@ -47,7 +47,7 @@ public PromotionListVm getPromotions(int pageNo, int pageSize, String promotionN Page promotionPage; - promotionPage = promotionRepository.findPromotions(promotionName.trim().toLowerCase(), couponCode.trim().toLowerCase(), startDate, endDate, pageable); + promotionPage = promotionRepository.findPromotions(promotionName.trim(), couponCode.trim(), startDate, endDate, pageable); List promotionDetailVmList = promotionPage .getContent() diff --git a/promotion/src/test/java/com/yas/promotion/service/PromotionServiceTest.java b/promotion/src/test/java/com/yas/promotion/service/PromotionServiceTest.java index 7eec8eb070..6dbebb7010 100644 --- a/promotion/src/test/java/com/yas/promotion/service/PromotionServiceTest.java +++ b/promotion/src/test/java/com/yas/promotion/service/PromotionServiceTest.java @@ -1,5 +1,6 @@ package com.yas.promotion.service; +import com.yas.promotion.PromotionApplication; import com.yas.promotion.exception.DuplicatedException; import com.yas.promotion.model.Promotion; import com.yas.promotion.repository.PromotionRepository; @@ -7,8 +8,11 @@ import com.yas.promotion.viewmodel.PromotionDetailVm; import com.yas.promotion.viewmodel.PromotionListVm; import com.yas.promotion.viewmodel.PromotionPostVm; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; @@ -25,24 +29,20 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - +@SpringBootTest(classes = PromotionApplication.class) class PromotionServiceTest { + @Autowired private PromotionRepository promotionRepository; - + @Autowired private PromotionService promotionService; private Promotion promotion1; private Promotion promotion2; private PromotionPostVm promotionPostVm; - private List promotionList; @BeforeEach void setUp() { - promotionRepository = mock(PromotionRepository.class); - promotionService = new PromotionService(promotionRepository); - promotion1 = Promotion.builder() - .id(1L) .name("Promotion 1") .slug("promotion-1") .description("Description 1") @@ -53,9 +53,9 @@ void setUp() { .startDate(ZonedDateTime.now()) .endDate(ZonedDateTime.now().plusDays(30)) .build(); + promotion1 = promotionRepository.save(promotion1); promotion2 = Promotion.builder() - .id(2L) .name("Promotion 2") .slug("promotion-2") .description("Description 2") @@ -66,9 +66,16 @@ void setUp() { .startDate(ZonedDateTime.now().minusDays(30)) .endDate(ZonedDateTime.now().plusDays(60)) .build(); + promotion2 = promotionRepository.save(promotion2); + } - promotionList = Arrays.asList(promotion1, promotion2); + @AfterEach + void tearDown() { + promotionRepository.deleteAll(); + } + @Test + void createPromotion_ThenSuccess() { promotionPostVm = PromotionPostVm.builder() .name("Promotion 3") .slug("promotion-3") @@ -80,54 +87,28 @@ void setUp() { .startDate(ZonedDateTime.now().plusDays(60)) .endDate(ZonedDateTime.now().plusDays(90)) .build(); - } - - @Test - void createPromotion_ThenSuccess() { - Promotion promotion = Promotion.builder() - .name(promotionPostVm.name()) - .slug(promotionPostVm.slug()) - .description(promotionPostVm.description()) - .couponCode(promotionPostVm.couponCode()) - .discountPercentage(promotionPostVm.discountPercentage()) - .discountAmount(promotionPostVm.discountAmount()) - .isActive(true) - .startDate(promotionPostVm.startDate()) - .endDate(promotionPostVm.endDate()) - .build(); - - when(promotionRepository.findBySlugAndIsActiveTrue(promotion.getSlug())).thenReturn(Optional.empty()); - when(promotionRepository.saveAndFlush(any(Promotion.class))).thenReturn(promotion); PromotionDetailVm result = promotionService.createPromotion(promotionPostVm); - - assertEquals(promotion.getSlug(), result.slug()); + assertEquals(promotionPostVm.slug(), result.slug()); + assertEquals(promotionPostVm.name(), result.name()); assertEquals(true, result.isActive()); } @Test void createPromotion_WhenExistedSlug_ThenDuplicatedExceptionThrown() { - String slug = "test-promotion"; PromotionPostVm promotionPostVm = PromotionPostVm.builder() - .slug(slug) + .slug(promotion1.getSlug()) .build(); - - when(promotionRepository.findBySlugAndIsActiveTrue(slug)).thenReturn(Optional.of(new Promotion())); assertThrows(DuplicatedException.class, () -> promotionService.createPromotion(promotionPostVm), - String.format(Constants.ERROR_CODE.SLUG_ALREADY_EXITED, slug)); - + String.format(Constants.ERROR_CODE.SLUG_ALREADY_EXITED, promotionPostVm.slug())); } @Test void getPromotionList_ThenSuccess() { - Page promotionPage = new PageImpl<>(promotionList); - when(promotionRepository.findPromotions(anyString(), anyString(), any(ZonedDateTime.class), any(ZonedDateTime.class), any(Pageable.class))) - .thenReturn(promotionPage); - - PromotionListVm result = promotionService.getPromotions(0, 5, "Promotion", "code", ZonedDateTime.now(), ZonedDateTime.now().plusDays(30)); - + PromotionListVm result = promotionService.getPromotions(0, 5, + "Promotion", "code", + ZonedDateTime.now().minusDays(120), ZonedDateTime.now().plusDays(120)); assertEquals(2, result.promotionDetailVmList().size()); - PromotionDetailVm promotionDetailVm = result.promotionDetailVmList().get(0); assertEquals("promotion-1", promotionDetailVm.slug()); } diff --git a/promotion/src/test/resources/application.properties b/promotion/src/test/resources/application.properties index 0140ebbfcb..a807b00a8d 100644 --- a/promotion/src/test/resources/application.properties +++ b/promotion/src/test/resources/application.properties @@ -1,13 +1,20 @@ # Setting Spring context path & port server.servlet.context-path=/v1 server.port=8092 -spring.jpa.hibernate.ddl-auto=update # Setting Spring profile spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.promotion + +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false + +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test diff --git a/rating/src/test/java/com/yas/rating/config/SecurityConfig.java b/rating/src/test/java/com/yas/rating/config/SecurityConfig.java deleted file mode 100644 index f5cb6e4bbe..0000000000 --- a/rating/src/test/java/com/yas/rating/config/SecurityConfig.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.yas.rating.config; - -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; - -@TestConfiguration -public class SecurityConfig { - @Bean - public WebSecurityCustomizer webSecurityCustomizer() { - return web -> web.ignoring() - .requestMatchers(HttpMethod.POST, "/backoffice/**") - .requestMatchers(HttpMethod.PUT, "/backoffice/**") - .requestMatchers(HttpMethod.GET, "/backoffice/**") - .requestMatchers(HttpMethod.DELETE, "/backoffice/**"); - } -} diff --git a/rating/src/test/java/com/yas/rating/model/RatingTest.java b/rating/src/test/java/com/yas/rating/model/RatingTest.java deleted file mode 100644 index e5982e9613..0000000000 --- a/rating/src/test/java/com/yas/rating/model/RatingTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.yas.rating.model; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -class RatingTest { - @Test - void equalsVerifier() { - Rating rating1 = new Rating(); - rating1.setId(1L); - Rating rating2 = new Rating(); - rating2.setId(rating1.getId()); - assertThat(rating1).isEqualTo(rating2); - rating2.setId(2L); - assertThat(rating1).isNotEqualTo(rating2); - rating1.setId(null); - assertThat(rating1).isNotEqualTo(rating2); - } -} diff --git a/rating/src/test/java/com/yas/rating/service/RatingServiceTest.java b/rating/src/test/java/com/yas/rating/service/RatingServiceTest.java index bb9523dc07..0d6c3aac51 100644 --- a/rating/src/test/java/com/yas/rating/service/RatingServiceTest.java +++ b/rating/src/test/java/com/yas/rating/service/RatingServiceTest.java @@ -1,118 +1,142 @@ package com.yas.rating.service; +import com.yas.rating.RatingApplication; import com.yas.rating.model.Rating; import com.yas.rating.repository.RatingRepository; -import com.yas.rating.utils.AuthenticationUtils; import com.yas.rating.viewmodel.*; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; + +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.List; +import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +@SpringBootTest(classes = RatingApplication.class) class RatingServiceTest { - RatingRepository ratingRepository; - CustomerService customerService; - ProductService productService; - RatingService ratingService; - - OrderService orderService; - - RatingPostVm ratingPostVm; - List ratingList; + @Autowired + private RatingRepository ratingRepository; + @MockBean + private CustomerService customerService; + @MockBean + private OrderService orderService; + @Autowired + private RatingService ratingService; + private List ratingList; + private String userId = "user1"; @BeforeEach void setUp() { - ratingRepository = mock(RatingRepository.class); - customerService = mock(CustomerService.class); - productService = mock(ProductService.class); - orderService = mock(OrderService.class); - ratingService = new RatingService(ratingRepository, customerService, orderService); - - ratingList = List.of( Rating.builder() - .id(1L) .content("comment 1") - .ratingStar(2) + .ratingStar(4) .productId(1L) + .productName("product1") + .firstName("Duy") + .lastName("Nguyen") .build(), Rating.builder() - .id(1L) .content("comment 2") .ratingStar(2) .productId(1L) + .productName("product1") + .firstName("Hai") + .lastName("Le") + .build(), + Rating.builder() + .content("comment 3") + .ratingStar(3) + .productId(2L) + .productName("product2") + .firstName("Cuong") + .lastName("Tran") .build() ); + ratingRepository.saveAll(ratingList); - ratingPostVm = RatingPostVm.builder() - .productId(1L) - .content("comment 1") - .star(5) - .build(); + } + + @AfterEach + void tearDown() { + ratingRepository.deleteAll(); } @Test - void getRatingList_WhenProductIsExist_Sucsess() { + void getRatingList_ValidProductId_ShouldSuccess() { int totalPage = 1; int pageNo = 0; int pageSize = 10; - var pageCaptor = ArgumentCaptor.forClass(Pageable.class); - Page ratingPage = mock(Page.class); - - when(ratingRepository.findByProductId(anyLong(), any())).thenReturn(ratingPage); - when(ratingPage.getContent()).thenReturn(ratingList); - when(ratingPage.getTotalPages()).thenReturn(totalPage); - when(ratingPage.getTotalElements()).thenReturn(2L); RatingListVm actualResponse = ratingService.getRatingListByProductId(1L, pageNo, pageSize); - - verify(ratingRepository).findByProductId(anyLong(), pageCaptor.capture()); - assertThat(actualResponse.totalPages()).isEqualTo(totalPage); - assertThat(actualResponse.totalElements()).isEqualTo(2L); - for (int i = 0; i < actualResponse.totalElements(); i++) { - Rating rating = ratingList.get(i); - assertThat(actualResponse.ratingList().get(i).id()).isEqualTo(rating.getId()); - assertThat(actualResponse.ratingList().get(i).star()).isEqualTo(rating.getRatingStar()); - assertThat(actualResponse.ratingList().get(i).content()).isEqualTo(rating.getContent()); - assertThat(actualResponse.ratingList().get(i).productId()).isEqualTo(rating.getProductId()); - } + assertEquals(totalPage, actualResponse.totalPages()); + assertEquals(2, actualResponse.totalElements()); + assertEquals(2, actualResponse.ratingList().size()); } @Test - void createProduct_WhenProductIsExist_ShouldReturnSuccess() { - Rating savedRating = mock(Rating.class); - var ratingCaptor = ArgumentCaptor.forClass(Rating.class); - - try (MockedStatic utilities = Mockito.mockStatic(AuthenticationUtils.class)) { - utilities.when(AuthenticationUtils::extractUserId).thenReturn("id"); + void getRatingListWithFilter_ValidFilterData_ShouldReturnSuccess() { + String proName = "product2"; + String firstName = "Cuong"; + String lastName = "Tran"; + String cusName = firstName + " " + lastName; + String message = "comment 3"; + ZonedDateTime createdFrom = ZonedDateTime.now().minusDays(30); + ZonedDateTime createdTo = ZonedDateTime.now().plusDays(30); + int totalPage = 1; + int pageNo = 0; + int pageSize = 10; + RatingListVm actualResponse = ratingService.getRatingListWithFilter(proName, cusName, message, createdFrom, createdTo, pageNo, pageSize); + assertEquals(totalPage, actualResponse.totalPages()); + assertEquals(1, actualResponse.totalElements()); + assertEquals(proName, actualResponse.ratingList().getFirst().productName()); + assertEquals(message, actualResponse.ratingList().getFirst().content()); + assertEquals(firstName, actualResponse.ratingList().getFirst().firstName()); + assertEquals(lastName, actualResponse.ratingList().getFirst().lastName()); + } - when(orderService.checkOrderExistsByProductAndUserWithStatus( - ratingPostVm.productId() - )).thenReturn(new OrderExistsByProductAndUserGetVm(true)); - when(ratingRepository.existsByCreatedByAndProductId( - "id", - ratingPostVm.productId() - )).thenReturn(false); - when(customerService.getCustomer()).thenReturn(mock(CustomerVm.class)); - when(ratingRepository.saveAndFlush(ratingCaptor.capture())).thenReturn(savedRating); + @Test + void createRating_ValidRatingData_ShouldSuccess() { + Jwt jwt = mock(Jwt.class); + JwtAuthenticationToken authentication = mock(JwtAuthenticationToken.class); + SecurityContextHolder.getContext().setAuthentication(authentication); + when(authentication.getToken()).thenReturn(jwt); + when(authentication.getName()).thenReturn(userId); + when(jwt.getSubject()).thenReturn(userId); + when(orderService.checkOrderExistsByProductAndUserWithStatus(anyLong())).thenReturn(new OrderExistsByProductAndUserGetVm(true)); + when(customerService.getCustomer()).thenReturn(new CustomerVm(userId, null, "Cuong", "Tran")); + + RatingPostVm ratingPostVm = RatingPostVm.builder().content("comment 4").productName("product3").star(4).productId(3L).build(); + RatingVm ratingVm = ratingService.createRating(ratingPostVm); + assertEquals(ratingPostVm.productName(), ratingVm.productName()); + assertEquals(ratingPostVm.content(), ratingVm.content()); + assertEquals(ratingPostVm.star(), ratingVm.star()); + } - RatingVm actualResponse = ratingService.createRating(ratingPostVm); + @Test + void deleteRating_ValidRatingId_ShouldSuccess() { + Long id = ratingRepository.findAll().getFirst().getId(); + ratingService.deleteRating(id); + Optional rating = ratingRepository.findById(id); + assertFalse(rating.isPresent()); + } - verify(ratingRepository).saveAndFlush(ratingCaptor.capture()); - Rating ratingValue = ratingCaptor.getValue(); - assertThat(ratingValue.getContent()).isEqualTo(ratingPostVm.content()); - assertThat(ratingValue.getRatingStar()).isEqualTo(ratingPostVm.star()); - assertThat(ratingValue.getProductId()).isEqualTo(ratingPostVm.productId()); - } + @Test + void calculateAverageStar_ValidProductId_ShouldSuccess() { + Double averageStar = ratingService.calculateAverageStar(1L); + assertEquals(3, averageStar); } } diff --git a/rating/src/test/resources/application.properties b/rating/src/test/resources/application.properties index c0c8fba74c..166c2fd1f7 100644 --- a/rating/src/test/resources/application.properties +++ b/rating/src/test/resources/application.properties @@ -1,7 +1,10 @@ # Setting Spring context path & port -server.servlet.context-path=/v1 +server.servlet.context-path=/rating server.port=8089 +# Setting Spring profile +spring.profiles.active=test + spring.datasource.url=jdbc:h2:mem:testdb;NON_KEYWORDS=VALUE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa @@ -9,12 +12,8 @@ spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false -# Setting Spring profile -spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true - -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.rating \ No newline at end of file +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test \ No newline at end of file diff --git a/tax/src/test/resources/application.properties b/tax/src/test/resources/application.properties index b76d74cc15..fb5ecc48a6 100644 --- a/tax/src/test/resources/application.properties +++ b/tax/src/test/resources/application.properties @@ -2,6 +2,9 @@ server.servlet.context-path=/v1 server.port=8091 +# Setting Spring profile +spring.profiles.active=test + spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa @@ -9,13 +12,9 @@ spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update +spring.liquibase.enabled=false -# Setting Spring profile -spring.profiles.active=test -springdoc.swagger-ui.enabled=true -springdoc.api-docs.enabled=true - -# swagger-ui custom path -springdoc.swagger-ui.path=/swagger-ui.html -springdoc.packagesToScan=com.yas.tax +spring.security.oauth2.resourceserver.jwt.issuer-uri=test +springdoc.oauthflow.authorization-url=test +springdoc.oauthflow.token-url=test From ffbde4141f24fde1ca7992bdaca3fc51584d07c4 Mon Sep 17 00:00:00 2001 From: khanhtranduy <130121475+khanhtranduy@users.noreply.github.com> Date: Fri, 21 Jun 2024 15:43:17 +0700 Subject: [PATCH 2/2] Fix unit test failures --- .../controller/BaseControllerTest.java | 31 +++++++++++++++++++ .../controller/BrandControllerTest.java | 22 +++++-------- .../controller/CategoryControllerTest.java | 14 ++------- .../ProductAttributeControllerTest.java | 31 ++++--------------- .../ProductAttributeGroupControllerTest.java | 11 ++----- .../ProductAttributeValueControllerTest.java | 12 ++----- .../ProductOptionControllerTest.java | 11 ++----- .../ProductOptionValueControllerTest.java | 9 ++---- 8 files changed, 58 insertions(+), 83 deletions(-) create mode 100644 product/src/test/java/com/yas/product/controller/BaseControllerTest.java diff --git a/product/src/test/java/com/yas/product/controller/BaseControllerTest.java b/product/src/test/java/com/yas/product/controller/BaseControllerTest.java new file mode 100644 index 0000000000..d5ee4f0f23 --- /dev/null +++ b/product/src/test/java/com/yas/product/controller/BaseControllerTest.java @@ -0,0 +1,31 @@ +package com.yas.product.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.servlet.client.MockMvcWebTestClient; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class BaseControllerTest { + protected WebTestClient webTestClient; + @Autowired + private WebApplicationContext context; + + protected final String USERNAME = "admin"; + protected final String ROLE = "ADMIN"; + + void setup() { + this.webTestClient = MockMvcWebTestClient + .bindToApplicationContext(context) + .apply(springSecurity()) + .defaultRequest(MockMvcRequestBuilders.get("/").with(SecurityMockMvcRequestPostProcessors.csrf())) + .configureClient() + .build(); + } +} diff --git a/product/src/test/java/com/yas/product/controller/BrandControllerTest.java b/product/src/test/java/com/yas/product/controller/BrandControllerTest.java index 7ec401a08b..a19eefccc0 100644 --- a/product/src/test/java/com/yas/product/controller/BrandControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/BrandControllerTest.java @@ -1,6 +1,5 @@ package com.yas.product.controller; -import com.yas.product.ProductApplication; import com.yas.product.model.Brand; import com.yas.product.model.Product; import com.yas.product.repository.BrandRepository; @@ -12,40 +11,33 @@ import org.junit.jupiter.api.BeforeEach; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.EntityExchangeResult; -import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -public class BrandControllerTest { +public class BrandControllerTest extends BaseControllerTest{ @Autowired private BrandRepository brandRepository; @Autowired private ProductRepository productRepository; - @Autowired - private WebTestClient webTestClient; + private final Brand brand1 = new Brand(); private Long brandId; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; + private final String STORE_FRONT_URL = "/storefront/brands"; private final String BACK_OFFICE_URL = "/backoffice/brands"; private Long invalidId = 9999L; @BeforeEach void setup() { + super.setup(); brand1.setName("iphone13"); brand1.setSlug("iphone-13"); brand1.setProducts(List.of()); @@ -76,7 +68,8 @@ void listBrands_StoreFrontReturnList_Success() { @WithMockUser(username = USERNAME, roles = {ROLE}) void listBrands_BackOfficeReturnList_Success() { EntityExchangeResult> result = - webTestClient.get().uri(BACK_OFFICE_URL) + webTestClient + .get().uri(BACK_OFFICE_URL) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() @@ -119,7 +112,8 @@ void getBrand_FindIdBrand_Success() { @WithMockUser(username = USERNAME, roles = {ROLE}) void createBrand_SaveBrandPostVm_Success() { BrandPostVm brandPostVm = new BrandPostVm("samsung", "samsung", true); - EntityExchangeResult result = webTestClient.post().uri(BACK_OFFICE_URL) + EntityExchangeResult result = webTestClient + .post().uri(BACK_OFFICE_URL) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(brandPostVm)) .exchange() diff --git a/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java b/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java index 14bbc68e50..7cbf69f816 100644 --- a/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/CategoryControllerTest.java @@ -1,6 +1,5 @@ package com.yas.product.controller; -import com.yas.product.ProductApplication; import com.yas.product.model.Category; import com.yas.product.repository.CategoryRepository; import com.yas.product.viewmodel.category.CategoryGetDetailVm; @@ -11,38 +10,29 @@ import org.junit.jupiter.api.BeforeEach; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.EntityExchangeResult; -import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -class CategoryControllerTest { +class CategoryControllerTest extends BaseControllerTest { @Autowired private CategoryRepository categoryRepository; - @Autowired - private WebTestClient webTestClient; private Category category; private Long categoryId; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String STORE_FRONT_URL = "/storefront/categories"; private final String BACK_OFFICE_URL = "/backoffice/categories"; private final Long invalidId = 9999L; @BeforeEach void setUp() { + super.setup(); category = new Category(); category.setName("laptop"); category.setSlug("laptop-slug"); diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java index 3ff14af8e0..a0486203d2 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeControllerTest.java @@ -1,9 +1,5 @@ package com.yas.product.controller; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.yas.product.ProductApplication; -import com.yas.product.model.Brand; import com.yas.product.model.Product; import com.yas.product.model.attribute.ProductAttribute; import com.yas.product.model.attribute.ProductAttributeGroup; @@ -12,8 +8,6 @@ import com.yas.product.repository.ProductAttributeRepository; import com.yas.product.repository.ProductAttributeValueRepository; import com.yas.product.repository.ProductRepository; -import com.yas.product.viewmodel.category.CategoryGetDetailVm; -import com.yas.product.viewmodel.category.CategoryGetVm; import com.yas.product.viewmodel.error.ErrorVm; import com.yas.product.viewmodel.productattribute.ProductAttributeGetVm; import com.yas.product.viewmodel.productattribute.ProductAttributePostVm; @@ -21,28 +15,18 @@ import org.junit.jupiter.api.BeforeEach; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.EntityExchangeResult; -import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.reactive.function.BodyInserters; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Optional; -import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -class ProductAttributeControllerTest { +class ProductAttributeControllerTest extends BaseControllerTest { @Autowired private ProductAttributeRepository productAttributeRepository; @@ -52,18 +36,15 @@ class ProductAttributeControllerTest { private ProductRepository productRepository; @Autowired private ProductAttributeValueRepository productAttributeValueRepository; - @Autowired - private WebTestClient webTestClient; private Long productAttributeId; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String BACK_OFFICE_URL = "/backoffice/product-attribute"; private ProductAttribute productAttribute; private ProductAttributeGroup productAttributeGroup; private Long invalidId = 9999L; @BeforeEach - void setUp(){ + void setup(){ + super.setup(); productAttributeGroup = new ProductAttributeGroup(); productAttributeGroup.setName("Computer"); productAttributeGroup = productAttributeGroupRepository.save(productAttributeGroup); diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java index b39e19bc1b..4ef33ba862 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeGroupControllerTest.java @@ -25,15 +25,9 @@ import static org.junit.jupiter.api.Assertions.*; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -class ProductAttributeGroupControllerTest { - @Autowired - private WebTestClient webTestClient; +class ProductAttributeGroupControllerTest extends BaseControllerTest { @Autowired private ProductAttributeGroupRepository productAttributeGroupRepository; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String BACK_OFFICE_URL = "/backoffice/product-attribute-groups"; private ProductAttributeGroup productAttributeGroup1; private ProductAttributeGroup productAttributeGroup2; @@ -42,7 +36,8 @@ class ProductAttributeGroupControllerTest { private Long invalidId = 9999L; @BeforeEach - void setUp() { + void setup() { + super.setup(); productAttributeGroup1 = new ProductAttributeGroup(); productAttributeGroup2 = new ProductAttributeGroup(); productAttributeGroup1.setName("productAttributeGroupName1"); diff --git a/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java index f31cc811b4..f28f28e316 100644 --- a/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductAttributeValueControllerTest.java @@ -30,9 +30,7 @@ import static org.junit.jupiter.api.Assertions.*; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -public class ProductAttributeValueControllerTest { +public class ProductAttributeValueControllerTest extends BaseControllerTest { @Autowired private ProductAttributeGroupRepository productAttributeGroupRepository; @@ -42,11 +40,6 @@ public class ProductAttributeValueControllerTest { private ProductAttributeRepository productAttributeRepository; @Autowired private ProductRepository productRepository; - - @Autowired - private WebTestClient webTestClient; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String BACK_OFFICE_URL = "/backoffice/product-attribute-value"; private Long invalidId = 9999L; private ProductAttributeGroup productAttributeGroup; @@ -55,7 +48,8 @@ public class ProductAttributeValueControllerTest { private Product product; @BeforeEach - void Setup() { + public void setup() { + super.setup(); productAttributeGroup = new ProductAttributeGroup(); productAttributeGroup.setName("Computer"); productAttributeGroup = productAttributeGroupRepository.save(productAttributeGroup); diff --git a/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java index 542ead0b8f..a9b4ce85d4 100644 --- a/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductOptionControllerTest.java @@ -24,21 +24,16 @@ import static org.junit.jupiter.api.Assertions.*; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -public class ProductOptionControllerTest { +public class ProductOptionControllerTest extends BaseControllerTest{ @Autowired private ProductOptionRepository productOptionRepository; private ProductOption productOption; - @Autowired - private WebTestClient webTestClient; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String BACK_OFFICE_URL = "/backoffice/product-options"; private Long invalidId = 9999L; @BeforeEach - public void setUp() { + void setup() { + super.setup(); productOption = new ProductOption(); productOption.setName("camera"); productOption = productOptionRepository.save(productOption); diff --git a/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java b/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java index 87d30fffb0..9d76f5ebfe 100644 --- a/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java +++ b/product/src/test/java/com/yas/product/controller/ProductOptionValueControllerTest.java @@ -26,9 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -@SpringBootTest(classes = ProductApplication.class) -@AutoConfigureMockMvc -class ProductOptionValueControllerTest { +class ProductOptionValueControllerTest extends BaseControllerTest { @Autowired private ProductOptionValueRepository productOptionValueRepository; @Autowired @@ -38,16 +36,13 @@ class ProductOptionValueControllerTest { private ProductOptionValue productOptionValue; private ProductOption productOption; private Product product; - @Autowired - private WebTestClient webTestClient; - private final String USERNAME = "admin"; - private final String ROLE = "ADMIN"; private final String STORE_FRONT_URL = "/storefront/product-option-values"; private final String BACK_OFFICE_URL = "/backoffice/product-option-values"; private Long invalidId = 9999L; @BeforeEach void setup() { + super.setup(); product = Product.builder() .name(String.format("product")) .slug(String.format("slug"))