diff --git a/src/main/java/com/moabam/api/application/ItemService.java b/src/main/java/com/moabam/api/application/ItemService.java new file mode 100644 index 00000000..9d9aca77 --- /dev/null +++ b/src/main/java/com/moabam/api/application/ItemService.java @@ -0,0 +1,31 @@ +package com.moabam.api.application; + +import java.util.List; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.api.domain.repository.InventorySearchRepository; +import com.moabam.api.domain.repository.ItemSearchRepository; +import com.moabam.api.dto.ItemMapper; +import com.moabam.api.dto.ItemsResponse; + +import lombok.RequiredArgsConstructor; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class ItemService { + + private final ItemSearchRepository itemSearchRepository; + private final InventorySearchRepository inventorySearchRepository; + + public ItemsResponse getItems(Long memberId, ItemType type) { + List purchasedItems = inventorySearchRepository.findItems(memberId, type); + List notPurchasedItems = itemSearchRepository.findNotPurchasedItems(memberId, type); + + return ItemMapper.toItemsResponse(purchasedItems, notPurchasedItems); + } +} diff --git a/src/main/java/com/moabam/api/domain/entity/Inventory.java b/src/main/java/com/moabam/api/domain/entity/Inventory.java new file mode 100644 index 00000000..4921ab7d --- /dev/null +++ b/src/main/java/com/moabam/api/domain/entity/Inventory.java @@ -0,0 +1,52 @@ +package com.moabam.api.domain.entity; + +import static java.util.Objects.*; + +import org.hibernate.annotations.ColumnDefault; + +import com.moabam.global.common.entity.BaseTimeEntity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Table(name = "inventory", indexes = @Index(name = "idx_member_id", columnList = "member_id")) +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Inventory extends BaseTimeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "member_id", updatable = false, nullable = false) + private Long memberId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "item_id", updatable = false, nullable = false) + private Item item; + + @Column(name = "is_default", nullable = false) + @ColumnDefault("false") + private boolean isDefault; + + @Builder + private Inventory(Long memberId, Item item, boolean isDefault) { + this.memberId = requireNonNull(memberId); + this.item = requireNonNull(item); + this.isDefault = isDefault; + } +} diff --git a/src/main/java/com/moabam/api/domain/entity/Item.java b/src/main/java/com/moabam/api/domain/entity/Item.java new file mode 100644 index 00000000..defce5f4 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/entity/Item.java @@ -0,0 +1,90 @@ +package com.moabam.api.domain.entity; + +import static com.moabam.global.error.model.ErrorMessage.*; +import static java.util.Objects.*; + +import org.hibernate.annotations.ColumnDefault; + +import com.moabam.api.domain.entity.enums.ItemCategory; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.global.common.entity.BaseTimeEntity; +import com.moabam.global.error.exception.BadRequestException; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Table(name = "item") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Item extends BaseTimeEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Enumerated(value = EnumType.STRING) + @Column(name = "type", nullable = false) + private ItemType type; + + @Enumerated(value = EnumType.STRING) + @Column(name = "category", nullable = false) + private ItemCategory category; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "image", nullable = false) + private String image; + + @Column(name = "bug_price", nullable = false) + @ColumnDefault("0") + private int bugPrice; + + @Column(name = "golden_bug_price", nullable = false) + @ColumnDefault("0") + private int goldenBugPrice; + + @Column(name = "unlock_level", nullable = false) + @ColumnDefault("1") + private int unlockLevel; + + @Builder + private Item(ItemType type, ItemCategory category, String name, String image, int bugPrice, int goldenBugPrice, + Integer unlockLevel) { + this.type = requireNonNull(type); + this.category = requireNonNull(category); + this.name = requireNonNull(name); + this.image = requireNonNull(image); + this.bugPrice = validatePrice(bugPrice); + this.goldenBugPrice = validatePrice(goldenBugPrice); + this.unlockLevel = validateLevel(requireNonNullElse(unlockLevel, 1)); + } + + private int validatePrice(int price) { + if (price < 0) { + throw new BadRequestException(INVALID_PRICE); + } + + return price; + } + + private int validateLevel(int level) { + if (level < 1) { + throw new BadRequestException(INVALID_LEVEL); + } + + return level; + } +} diff --git a/src/main/java/com/moabam/api/domain/entity/enums/ItemCategory.java b/src/main/java/com/moabam/api/domain/entity/enums/ItemCategory.java new file mode 100644 index 00000000..581698c0 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/entity/enums/ItemCategory.java @@ -0,0 +1,6 @@ +package com.moabam.api.domain.entity.enums; + +public enum ItemCategory { + + SKIN; +} diff --git a/src/main/java/com/moabam/api/domain/entity/enums/ItemType.java b/src/main/java/com/moabam/api/domain/entity/enums/ItemType.java new file mode 100644 index 00000000..f21fbc68 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/entity/enums/ItemType.java @@ -0,0 +1,7 @@ +package com.moabam.api.domain.entity.enums; + +public enum ItemType { + + MORNING, + NIGHT; +} diff --git a/src/main/java/com/moabam/api/domain/repository/InventoryRepository.java b/src/main/java/com/moabam/api/domain/repository/InventoryRepository.java new file mode 100644 index 00000000..bac07502 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/repository/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.moabam.api.domain.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.moabam.api.domain.entity.Inventory; + +public interface InventoryRepository extends JpaRepository { + +} diff --git a/src/main/java/com/moabam/api/domain/repository/InventorySearchRepository.java b/src/main/java/com/moabam/api/domain/repository/InventorySearchRepository.java new file mode 100644 index 00000000..e15c017c --- /dev/null +++ b/src/main/java/com/moabam/api/domain/repository/InventorySearchRepository.java @@ -0,0 +1,33 @@ +package com.moabam.api.domain.repository; + +import static com.moabam.api.domain.entity.QInventory.*; +import static com.moabam.api.domain.entity.QItem.*; + +import java.util.List; + +import org.springframework.stereotype.Repository; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.global.common.util.DynamicQuery; +import com.querydsl.jpa.impl.JPAQueryFactory; + +import lombok.RequiredArgsConstructor; + +@Repository +@RequiredArgsConstructor +public class InventorySearchRepository { + + private final JPAQueryFactory jpaQueryFactory; + + public List findItems(Long memberId, ItemType type) { + return jpaQueryFactory.selectFrom(inventory) + .join(inventory.item, item) + .where( + DynamicQuery.generateEq(memberId, inventory.memberId::eq), + DynamicQuery.generateEq(type, inventory.item.type::eq)) + .orderBy(inventory.createdAt.desc()) + .select(item) + .fetch(); + } +} diff --git a/src/main/java/com/moabam/api/domain/repository/ItemRepository.java b/src/main/java/com/moabam/api/domain/repository/ItemRepository.java new file mode 100644 index 00000000..ae5eede0 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/repository/ItemRepository.java @@ -0,0 +1,9 @@ +package com.moabam.api.domain.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.moabam.api.domain.entity.Item; + +public interface ItemRepository extends JpaRepository { + +} diff --git a/src/main/java/com/moabam/api/domain/repository/ItemSearchRepository.java b/src/main/java/com/moabam/api/domain/repository/ItemSearchRepository.java new file mode 100644 index 00000000..8f799973 --- /dev/null +++ b/src/main/java/com/moabam/api/domain/repository/ItemSearchRepository.java @@ -0,0 +1,43 @@ +package com.moabam.api.domain.repository; + +import static com.moabam.api.domain.entity.QInventory.*; +import static com.moabam.api.domain.entity.QItem.*; + +import java.util.List; + +import org.springframework.stereotype.Repository; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.global.common.util.DynamicQuery; +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.jpa.impl.JPAQueryFactory; + +import lombok.RequiredArgsConstructor; + +@Repository +@RequiredArgsConstructor +public class ItemSearchRepository { + + private final JPAQueryFactory jpaQueryFactory; + + public List findNotPurchasedItems(Long memberId, ItemType type) { + return jpaQueryFactory.selectFrom(item) + .leftJoin(inventory) + .on(inventory.item.id.eq(item.id)) + .where( + DynamicQuery.generateEq(type, item.type::eq), + DynamicQuery.generateEq(memberId, this::filterByMemberId)) + .orderBy( + item.unlockLevel.asc(), + item.bugPrice.asc(), + item.goldenBugPrice.asc(), + item.name.asc()) + .fetch(); + } + + private BooleanExpression filterByMemberId(Long memberId) { + return inventory.memberId.isNull() + .or(inventory.memberId.ne(memberId)); + } +} diff --git a/src/main/java/com/moabam/api/dto/BugMapper.java b/src/main/java/com/moabam/api/dto/BugMapper.java index 57bea850..d596c6dd 100644 --- a/src/main/java/com/moabam/api/dto/BugMapper.java +++ b/src/main/java/com/moabam/api/dto/BugMapper.java @@ -5,7 +5,7 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; -@NoArgsConstructor(access = AccessLevel.PROTECTED) +@NoArgsConstructor(access = AccessLevel.PRIVATE) public final class BugMapper { public static BugResponse toBugResponse(Bug bug) { diff --git a/src/main/java/com/moabam/api/dto/ItemMapper.java b/src/main/java/com/moabam/api/dto/ItemMapper.java new file mode 100644 index 00000000..b468a5e4 --- /dev/null +++ b/src/main/java/com/moabam/api/dto/ItemMapper.java @@ -0,0 +1,33 @@ +package com.moabam.api.dto; + +import java.util.List; + +import com.moabam.api.domain.entity.Item; +import com.moabam.global.common.util.StreamUtils; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ItemMapper { + + public static ItemResponse toItemResponse(Item item) { + return ItemResponse.builder() + .id(item.getId()) + .type(item.getType().name()) + .category(item.getCategory().name()) + .name(item.getName()) + .image(item.getImage()) + .level(item.getUnlockLevel()) + .bugPrice(item.getBugPrice()) + .goldenBugPrice(item.getGoldenBugPrice()) + .build(); + } + + public static ItemsResponse toItemsResponse(List purchasedItems, List notPurchasedItems) { + return ItemsResponse.builder() + .purchasedItems(StreamUtils.map(purchasedItems, ItemMapper::toItemResponse)) + .notPurchasedItems(StreamUtils.map(notPurchasedItems, ItemMapper::toItemResponse)) + .build(); + } +} diff --git a/src/main/java/com/moabam/api/dto/ItemResponse.java b/src/main/java/com/moabam/api/dto/ItemResponse.java new file mode 100644 index 00000000..13c83ace --- /dev/null +++ b/src/main/java/com/moabam/api/dto/ItemResponse.java @@ -0,0 +1,17 @@ +package com.moabam.api.dto; + +import lombok.Builder; + +@Builder +public record ItemResponse( + Long id, + String type, + String category, + String name, + String image, + int level, + int bugPrice, + int goldenBugPrice +) { + +} diff --git a/src/main/java/com/moabam/api/dto/ItemsResponse.java b/src/main/java/com/moabam/api/dto/ItemsResponse.java new file mode 100644 index 00000000..a0d323c8 --- /dev/null +++ b/src/main/java/com/moabam/api/dto/ItemsResponse.java @@ -0,0 +1,13 @@ +package com.moabam.api.dto; + +import java.util.List; + +import lombok.Builder; + +@Builder +public record ItemsResponse( + List purchasedItems, + List notPurchasedItems +) { + +} diff --git a/src/main/java/com/moabam/api/dto/ProductMapper.java b/src/main/java/com/moabam/api/dto/ProductMapper.java index 0851d490..bd2fce60 100644 --- a/src/main/java/com/moabam/api/dto/ProductMapper.java +++ b/src/main/java/com/moabam/api/dto/ProductMapper.java @@ -3,11 +3,12 @@ import java.util.List; import com.moabam.api.domain.entity.Product; +import com.moabam.global.common.util.StreamUtils; import lombok.AccessLevel; import lombok.NoArgsConstructor; -@NoArgsConstructor(access = AccessLevel.PROTECTED) +@NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ProductMapper { public static ProductResponse toProductResponse(Product product) { @@ -22,9 +23,7 @@ public static ProductResponse toProductResponse(Product product) { public static ProductsResponse toProductsResponse(List products) { return ProductsResponse.builder() - .products(products.stream() - .map(ProductMapper::toProductResponse) - .toList()) + .products(StreamUtils.map(products, ProductMapper::toProductResponse)) .build(); } } diff --git a/src/main/java/com/moabam/api/presentation/ItemController.java b/src/main/java/com/moabam/api/presentation/ItemController.java new file mode 100644 index 00000000..47bd5880 --- /dev/null +++ b/src/main/java/com/moabam/api/presentation/ItemController.java @@ -0,0 +1,28 @@ +package com.moabam.api.presentation; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.moabam.api.application.ItemService; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.api.dto.ItemsResponse; + +import lombok.RequiredArgsConstructor; + +@RestController +@RequestMapping("/items") +@RequiredArgsConstructor +public class ItemController { + + private final ItemService itemService; + + @GetMapping + @ResponseStatus(HttpStatus.OK) + public ItemsResponse getItems(@RequestParam ItemType type) { + return itemService.getItems(1L, type); + } +} diff --git a/src/main/java/com/moabam/api/presentation/ProductController.java b/src/main/java/com/moabam/api/presentation/ProductController.java index c2231d5b..7a686810 100644 --- a/src/main/java/com/moabam/api/presentation/ProductController.java +++ b/src/main/java/com/moabam/api/presentation/ProductController.java @@ -1,8 +1,9 @@ package com.moabam.api.presentation; -import org.springframework.http.ResponseEntity; +import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.moabam.api.application.ProductService; @@ -18,7 +19,8 @@ public class ProductController { private final ProductService productService; @GetMapping - public ResponseEntity getProducts() { - return ResponseEntity.ok(productService.getProducts()); + @ResponseStatus(HttpStatus.OK) + public ProductsResponse getProducts() { + return productService.getProducts(); } } diff --git a/src/main/java/com/moabam/global/common/util/StreamUtils.java b/src/main/java/com/moabam/global/common/util/StreamUtils.java new file mode 100644 index 00000000..2820d908 --- /dev/null +++ b/src/main/java/com/moabam/global/common/util/StreamUtils.java @@ -0,0 +1,17 @@ +package com.moabam.global.common.util; + +import java.util.List; +import java.util.function.Function; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class StreamUtils { + + public static List map(List list, Function mapper) { + return list.stream() + .map(mapper) + .toList(); + } +} diff --git a/src/main/java/com/moabam/global/error/handler/GlobalExceptionHandler.java b/src/main/java/com/moabam/global/error/handler/GlobalExceptionHandler.java index 2dc1f65d..b641f69b 100644 --- a/src/main/java/com/moabam/global/error/handler/GlobalExceptionHandler.java +++ b/src/main/java/com/moabam/global/error/handler/GlobalExceptionHandler.java @@ -1,8 +1,11 @@ package com.moabam.global.error.handler; +import static com.moabam.global.error.model.ErrorMessage.*; + import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.validation.FieldError; @@ -10,6 +13,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import com.moabam.global.error.exception.BadRequestException; import com.moabam.global.error.exception.ConflictException; @@ -18,7 +22,6 @@ import com.moabam.global.error.exception.MoabamException; import com.moabam.global.error.exception.NotFoundException; import com.moabam.global.error.exception.UnauthorizedException; -import com.moabam.global.error.model.ErrorMessage; import com.moabam.global.error.model.ErrorResponse; @RestControllerAdvice @@ -76,6 +79,17 @@ protected ErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotV validation.put(fieldError.getField(), fieldError.getDefaultMessage()); } - return new ErrorResponse(ErrorMessage.INVALID_REQUEST_FIELD.getMessage(), validation); + return new ErrorResponse(INVALID_REQUEST_FIELD.getMessage(), validation); + } + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ErrorResponse handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) { + String typeName = Optional.ofNullable(exception.getRequiredType()) + .map(Class::getSimpleName) + .orElse(""); + String message = String.format(INVALID_REQUEST_VALUE_TYPE_FORMAT.getMessage(), exception.getValue(), typeName); + + return new ErrorResponse(message, null); } } diff --git a/src/main/java/com/moabam/global/error/model/ErrorMessage.java b/src/main/java/com/moabam/global/error/model/ErrorMessage.java index 4421ceea..3944c5b0 100644 --- a/src/main/java/com/moabam/global/error/model/ErrorMessage.java +++ b/src/main/java/com/moabam/global/error/model/ErrorMessage.java @@ -8,6 +8,7 @@ public enum ErrorMessage { INVALID_REQUEST_FIELD("올바른 요청 정보가 아닙니다."), + INVALID_REQUEST_VALUE_TYPE_FORMAT("'%s' 값은 유효한 %s 값이 아닙니다."), ROOM_NOT_FOUND("존재하지 않는 방 입니다."), ROOM_MAX_USER_COUNT_MODIFY_FAIL("잘못된 최대 인원수 설정입니다."), @@ -26,6 +27,7 @@ public enum ErrorMessage { INVALID_BUG_COUNT("벌레 개수는 0 이상이어야 합니다."), INVALID_PRICE("가격은 0 이상이어야 합니다."), INVALID_QUANTITY("수량은 1 이상이어야 합니다."), + INVALID_LEVEL("레벨은 1 이상이어야 합니다."), FCM_INIT_FAILED("파이어베이스 설정을 실패했습니다."), FCM_TOKEN_NOT_FOUND("해당 유저는 접속 중이 아닙니다."), diff --git a/src/test/java/com/moabam/api/application/ItemServiceTest.java b/src/test/java/com/moabam/api/application/ItemServiceTest.java new file mode 100644 index 00000000..cc2b0a43 --- /dev/null +++ b/src/test/java/com/moabam/api/application/ItemServiceTest.java @@ -0,0 +1,57 @@ +package com.moabam.api.application; + +import static com.moabam.fixture.ItemFixture.*; +import static java.util.Collections.*; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.BDDMockito.*; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.api.domain.repository.InventorySearchRepository; +import com.moabam.api.domain.repository.ItemSearchRepository; +import com.moabam.api.dto.ItemResponse; +import com.moabam.api.dto.ItemsResponse; +import com.moabam.global.common.util.StreamUtils; + +@ExtendWith(MockitoExtension.class) +class ItemServiceTest { + + @InjectMocks + ItemService itemService; + + @Mock + ItemSearchRepository itemSearchRepository; + + @Mock + InventorySearchRepository inventorySearchRepository; + + @DisplayName("아이템 목록을 조회한다.") + @Test + void get_products_success() { + // given + Long memberId = 1L; + ItemType type = ItemType.MORNING; + Item item1 = morningSantaSkin().build(); + Item item2 = morningKillerSkin().build(); + given(inventorySearchRepository.findItems(memberId, type)).willReturn(List.of(item1, item2)); + given(itemSearchRepository.findNotPurchasedItems(memberId, type)).willReturn(emptyList()); + + // when + ItemsResponse response = itemService.getItems(memberId, type); + + // then + List purchasedItemNames = StreamUtils.map(response.purchasedItems(), ItemResponse::name); + assertThat(response.purchasedItems()).hasSize(2); + assertThat(purchasedItemNames).containsExactly(MORNING_SANTA_SKIN_NAME, MORNING_KILLER_SKIN_NAME); + assertThat(response.notPurchasedItems()).isEmpty(); + } +} diff --git a/src/test/java/com/moabam/api/application/ProductServiceTest.java b/src/test/java/com/moabam/api/application/ProductServiceTest.java index f3445bd3..bb63597f 100644 --- a/src/test/java/com/moabam/api/application/ProductServiceTest.java +++ b/src/test/java/com/moabam/api/application/ProductServiceTest.java @@ -17,6 +17,7 @@ import com.moabam.api.domain.repository.ProductRepository; import com.moabam.api.dto.ProductResponse; import com.moabam.api.dto.ProductsResponse; +import com.moabam.global.common.util.StreamUtils; @ExtendWith(MockitoExtension.class) class ProductServiceTest { @@ -39,10 +40,8 @@ void get_products_success() { ProductsResponse response = productService.getProducts(); // then - List productNames = response.products().stream() - .map(ProductResponse::name) - .toList(); + List productNames = StreamUtils.map(response.products(), ProductResponse::name); assertThat(response.products()).hasSize(2); - assertThat(productNames).containsOnly(BUG_PRODUCT_NAME, BUG_PRODUCT_NAME); + assertThat(productNames).containsExactly(BUG_PRODUCT_NAME, BUG_PRODUCT_NAME); } } diff --git a/src/test/java/com/moabam/api/domain/repository/InventorySearchRepositoryTest.java b/src/test/java/com/moabam/api/domain/repository/InventorySearchRepositoryTest.java new file mode 100644 index 00000000..83463363 --- /dev/null +++ b/src/test/java/com/moabam/api/domain/repository/InventorySearchRepositoryTest.java @@ -0,0 +1,67 @@ +package com.moabam.api.domain.repository; + +import static com.moabam.fixture.InventoryFixture.*; +import static com.moabam.fixture.ItemFixture.*; +import static org.assertj.core.api.Assertions.*; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; + +@SpringBootTest +@Transactional(readOnly = true) +class InventorySearchRepositoryTest { + + @Autowired + ItemRepository itemRepository; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + InventorySearchRepository inventorySearchRepository; + + @DisplayName("타입으로 인벤토리에 있는 아이템 목록을 구매일 순으로 조회한다.") + @Test + void find_items_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().build()); + inventoryRepository.save(inventory(memberId, morningSantaSkin)); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().build()); + inventoryRepository.save(inventory(memberId, morningKillerSkin)); + Item nightMageSkin = itemRepository.save(nightMageSkin()); + inventoryRepository.save(inventory(memberId, nightMageSkin)); + + // when + List actual = inventorySearchRepository.findItems(memberId, ItemType.MORNING); + + // then + assertThat(actual).hasSize(2) + .containsExactly(morningKillerSkin, morningSantaSkin); + } + + @DisplayName("인벤토리에 해당하는 타입의 아이템이 없으면 빈 목록을 조회한다.") + @Test + void find_empty_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().build()); + inventoryRepository.save(inventory(memberId, morningSantaSkin)); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().build()); + inventoryRepository.save(inventory(memberId, morningKillerSkin)); + + // when + List actual = inventorySearchRepository.findItems(memberId, ItemType.NIGHT); + + // then + assertThat(actual).isEmpty(); + } +} diff --git a/src/test/java/com/moabam/api/domain/repository/ItemSearchRepositoryTest.java b/src/test/java/com/moabam/api/domain/repository/ItemSearchRepositoryTest.java new file mode 100644 index 00000000..c4d41b15 --- /dev/null +++ b/src/test/java/com/moabam/api/domain/repository/ItemSearchRepositoryTest.java @@ -0,0 +1,96 @@ +package com.moabam.api.domain.repository; + +import static com.moabam.fixture.InventoryFixture.*; +import static com.moabam.fixture.ItemFixture.*; +import static org.assertj.core.api.Assertions.*; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; + +@SpringBootTest +@Transactional(readOnly = true) +class ItemSearchRepositoryTest { + + @Autowired + ItemRepository itemRepository; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + ItemSearchRepository itemSearchRepository; + + @DisplayName("타입으로 구매하지 않은 아이템 목록을 조회한다.") + @Test + void find_not_purchased_items_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().build()); + inventoryRepository.save(inventory(memberId, morningSantaSkin)); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().build()); + itemRepository.save(nightMageSkin()); + + // when + List actual = itemSearchRepository.findNotPurchasedItems(memberId, ItemType.MORNING); + + // then + assertThat(actual).hasSize(1) + .containsExactly(morningKillerSkin); + } + + @DisplayName("구매하지 않은 아이템 목록은 레벨 순으로 정렬된다.") + @Test + void find_not_purchased_items_sorted_by_level_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().unlockLevel(5).build()); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().unlockLevel(1).build()); + + // when + List actual = itemSearchRepository.findNotPurchasedItems(memberId, ItemType.MORNING); + + // then + assertThat(actual).hasSize(2) + .containsExactly(morningKillerSkin, morningSantaSkin); + } + + @DisplayName("레벨이 같으면 가격 순으로 정렬된다.") + @Test + void find_not_purchased_items_sorted_by_price_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().bugPrice(10).build()); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().bugPrice(20).build()); + + // when + List actual = itemSearchRepository.findNotPurchasedItems(memberId, ItemType.MORNING); + + // then + assertThat(actual).hasSize(2) + .containsExactly(morningSantaSkin, morningKillerSkin); + } + + @DisplayName("레벨과 가격이 같으면 이름 순으로 정렬된다.") + @Test + void find_not_purchased_items_sorted_by_name_success() { + // given + Long memberId = 1L; + Item morningSantaSkin = itemRepository.save(morningSantaSkin().build()); + Item morningKillerSkin = itemRepository.save(morningKillerSkin().build()); + + // when + List actual = itemSearchRepository.findNotPurchasedItems(memberId, ItemType.MORNING); + + // then + assertThat(actual).hasSize(2) + .containsExactly(morningSantaSkin, morningKillerSkin); + } +} diff --git a/src/test/java/com/moabam/api/presentation/ItemControllerTest.java b/src/test/java/com/moabam/api/presentation/ItemControllerTest.java new file mode 100644 index 00000000..eee2e9a4 --- /dev/null +++ b/src/test/java/com/moabam/api/presentation/ItemControllerTest.java @@ -0,0 +1,64 @@ +package com.moabam.api.presentation; + +import static java.nio.charset.StandardCharsets.*; +import static java.util.Collections.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.util.List; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.moabam.api.application.ItemService; +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemType; +import com.moabam.api.dto.ItemMapper; +import com.moabam.api.dto.ItemsResponse; +import com.moabam.fixture.ItemFixture; + +@SpringBootTest +@AutoConfigureMockMvc +class ItemControllerTest { + + @Autowired + MockMvc mockMvc; + + @Autowired + ObjectMapper objectMapper; + + @MockBean + ItemService itemService; + + @DisplayName("아이템 목록을 조회한다.") + @Test + void get_items_success() throws Exception { + // given + Long memberId = 1L; + ItemType type = ItemType.MORNING; + Item item1 = ItemFixture.morningSantaSkin().build(); + Item item2 = ItemFixture.morningKillerSkin().build(); + ItemsResponse expected = ItemMapper.toItemsResponse(List.of(item1, item2), emptyList()); + given(itemService.getItems(memberId, type)).willReturn(expected); + + // expected + String content = mockMvc.perform(get("/items") + .param("type", ItemType.MORNING.name())) + .andDo(print()) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getContentAsString(UTF_8); + ItemsResponse actual = objectMapper.readValue(content, ItemsResponse.class); + Assertions.assertThat(actual).isEqualTo(expected); + } +} diff --git a/src/test/java/com/moabam/api/presentation/ProductControllerTest.java b/src/test/java/com/moabam/api/presentation/ProductControllerTest.java index f18b3236..a14c21c8 100644 --- a/src/test/java/com/moabam/api/presentation/ProductControllerTest.java +++ b/src/test/java/com/moabam/api/presentation/ProductControllerTest.java @@ -46,7 +46,7 @@ void get_products_success() throws Exception { ProductsResponse expected = ProductMapper.toProductsResponse(List.of(product1, product2)); given(productService.getProducts()).willReturn(expected); - // when & then + // expected String content = mockMvc.perform(get("/products")) .andDo(print()) .andExpect(status().isOk()) diff --git a/src/test/java/com/moabam/fixture/InventoryFixture.java b/src/test/java/com/moabam/fixture/InventoryFixture.java new file mode 100644 index 00000000..357443dc --- /dev/null +++ b/src/test/java/com/moabam/fixture/InventoryFixture.java @@ -0,0 +1,14 @@ +package com.moabam.fixture; + +import com.moabam.api.domain.entity.Inventory; +import com.moabam.api.domain.entity.Item; + +public class InventoryFixture { + + public static Inventory inventory(Long memberId, Item item) { + return Inventory.builder() + .memberId(memberId) + .item(item) + .build(); + } +} diff --git a/src/test/java/com/moabam/fixture/ItemFixture.java b/src/test/java/com/moabam/fixture/ItemFixture.java new file mode 100644 index 00000000..3d95487f --- /dev/null +++ b/src/test/java/com/moabam/fixture/ItemFixture.java @@ -0,0 +1,40 @@ +package com.moabam.fixture; + +import com.moabam.api.domain.entity.Item; +import com.moabam.api.domain.entity.enums.ItemCategory; +import com.moabam.api.domain.entity.enums.ItemType; + +public class ItemFixture { + + public static final String MORNING_SANTA_SKIN_NAME = "산타 오목눈이"; + public static final String MORNING_SANTA_SKIN_IMAGE = "/item/morning_santa.png"; + public static final String MORNING_KILLER_SKIN_NAME = "킬러 오목눈이"; + public static final String MORNING_KILLER_SKIN_IMAGE = "/item/morning_killer.png"; + public static final String NIGHT_MAGE_SKIN_NAME = "메이지 부엉이"; + public static final String NIGHT_MAGE_SKIN_IMAGE = "/item/night_mage.png"; + + public static Item.ItemBuilder morningSantaSkin() { + return Item.builder() + .type(ItemType.MORNING) + .category(ItemCategory.SKIN) + .name(MORNING_SANTA_SKIN_NAME) + .image(MORNING_SANTA_SKIN_IMAGE); + } + + public static Item.ItemBuilder morningKillerSkin() { + return Item.builder() + .type(ItemType.MORNING) + .category(ItemCategory.SKIN) + .name(MORNING_KILLER_SKIN_NAME) + .image(MORNING_KILLER_SKIN_IMAGE); + } + + public static Item nightMageSkin() { + return Item.builder() + .type(ItemType.NIGHT) + .category(ItemCategory.SKIN) + .name(NIGHT_MAGE_SKIN_NAME) + .image(NIGHT_MAGE_SKIN_IMAGE) + .build(); + } +}