Skip to content

Commit

Permalink
Merge pull request #253 from Team-BC-1/test/Coupon
Browse files Browse the repository at this point in the history
쿠폰 관련 테스트 코드 추가
  • Loading branch information
vanillacake369 authored Feb 12, 2024
2 parents 6948e23 + 47e8c0a commit 5ead75f
Show file tree
Hide file tree
Showing 14 changed files with 746 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ public class CouponQueryService {

public Coupon checkCoupon(Long couponId, User buyer, CouponStatus status) {

Coupon coupon = findByCouponId(couponId);

if (!isCheckCouponUser(coupon, buyer)) {
throw new GlobalException(ResultCase.NOT_AUTHORIZED);
}
Coupon coupon = findCouponById(couponId, buyer);

if (!isCheckCouponStatus(coupon, status)) {
throw new GlobalException(ResultCase.COUPON_STATUS_CHANGE_FAIL);
Expand All @@ -37,16 +33,6 @@ public Coupon checkCoupon(Long couponId, User buyer, CouponStatus status) {
return coupon;
}

private Coupon findByCouponId(Long couponId) {
return couponRepository.findById(couponId).orElseThrow(
() -> new GlobalException(ResultCase.COUPON_NOT_FOUND)
);
}

private boolean isCheckCouponUser(Coupon coupon, User user) {
return coupon.getUser().getLoginId().equals(user.getLoginId());
}

private boolean isCheckCouponStatus(Coupon coupon, CouponStatus status) {
return coupon.getStatus().equals(status);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
package bc1.gream.domain.admin.controller;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import bc1.gream.domain.admin.dto.request.AdminCreateCouponRequestDto;
import bc1.gream.domain.admin.dto.request.AdminGetRefundRequestDto;
import bc1.gream.domain.admin.dto.request.AdminProductRequestDto;
import bc1.gream.domain.admin.dto.request.AdminRefundPassResponseDto;
import bc1.gream.domain.coupon.entity.DiscountType;
import bc1.gream.domain.coupon.provider.CouponProvider;
import bc1.gream.domain.product.service.command.ProductCommandService;
import bc1.gream.domain.user.entity.Refund;
import bc1.gream.domain.user.entity.UserRole;
import bc1.gream.domain.user.service.command.RefundCommandService;
import bc1.gream.domain.user.service.query.RefundQueryService;
import bc1.gream.global.security.WithMockCustomUser;
import bc1.gream.test.RefundTest;
import bc1.gream.test.UserTest;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -28,7 +40,7 @@
@WebMvcTest(controllers = AdminController.class)
@WithMockCustomUser(loginId = "adminId12", password = "adminPw12!", userRole = UserRole.ADMIN)
@ActiveProfiles("test")
class AdminControllerTest {
class AdminControllerTest implements RefundTest {

@Autowired
WebApplicationContext context;
Expand All @@ -49,9 +61,83 @@ class AdminControllerTest {
void setUp() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.alwaysDo(print())
.build();
}

@Test
void 신청된_환급_리스트를_관리자가_조회하는_컨트롤러_기능_성공_테스트() throws Exception {

// given
AdminGetRefundRequestDto requestDto = new AdminGetRefundRequestDto();

String json = objectMapper.writeValueAsString(requestDto);

List<Refund> responseList = new ArrayList<>();

for (int i = 0; i < 5; i++) {
responseList.add(TEST_REFUND);
}

given(refundQueryService.getRefunds()).willReturn(responseList);

// when - then
mockMvc.perform(get("/api/admin/refunds")
.content(json)
.contentType(MediaType.APPLICATION_JSON))
.andExpectAll(
status().isOk(),
jsonPath("$.code").value(0),
jsonPath("$.message").value("정상 처리 되었습니다"),
jsonPath("$.data[0].refundBank").value("농협은행"),
jsonPath("$.data[1].refundBank").value("농협은행"),
jsonPath("$.data[2].refundBank").value("농협은행"),
jsonPath("$.data[3].refundBank").value("농협은행"),
jsonPath("$.data[4].refundBank").value("농협은행")
);
}

@Test
void 관리자가_새로운_상품을_하는_컨트롤러_기능_성공_테스트() throws Exception {

// given
AdminProductRequestDto requestDto = AdminProductRequestDto.builder()
.brand("스타벅스")
.name("콜드브루")
.imageUrl("C:/")
.description("콜드브루")
.price(6000L)
.build();

String json = objectMapper.writeValueAsString(requestDto);

// when - then
mockMvc.perform(post("/api/admin/products")
.content(json)
.contentType(MediaType.APPLICATION_JSON))
.andExpectAll(
status().isOk(),
jsonPath("$.code").value(0),
jsonPath("$.message").value("정상 처리 되었습니다")
);
}

@Test
void 유저가_요청한_환급내역_관리자가_승인하는_컨트롤러_기능_성공_테스트() throws Exception {

// given
AdminRefundPassResponseDto responseDto = new AdminRefundPassResponseDto();
given(refundCommandService.approveRefund(any(Long.class))).willReturn(responseDto);

// when - then
mockMvc.perform(delete("/api/admin/refund/{id}", TEST_REFUND_ID))
.andExpectAll(
status().isOk(),
jsonPath("$.code").value(0),
jsonPath("$.message").value("정상 처리 되었습니다")
);
}

@Test
public void 새로운_쿠폰_가_정상요청() throws Exception {
// GIVEN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ class BuyQueryServiceTest implements BuyTest, CouponTest {
}

@Test
void 현재_진행중인_유저의_구매입찰_전체_조회_서비스_기능_성공_테스트() {
void 현재_진행중인_유저의_구매입찰에_쿠폰이_존재할때_전체_조회_서비스_기능_성공_테스트() {

// given
List<BuyCheckBidResponseDto> responseDtoList = new ArrayList<>();
Expand All @@ -150,25 +150,56 @@ class BuyQueryServiceTest implements BuyTest, CouponTest {
.buyId((long) i)
.price(1000L * i)
.discountPrice(1000L * i)
.coupon((i % 2 == 0) ? TEST_COUPON_FIX : null)
.coupon(TEST_COUPON_FIX)
.build();

responseDtoList.add(responseDto);
}
given(buyRepository.findAllBuyBidCoupon(any(User.class), any(LocalDateTime.class))).willReturn(responseDtoList);
given(buyRepository.findAllBuyBidCoupon(any(User.class))).willReturn(responseDtoList);

// when
List<BuyCheckBidResponseDto> resultList = buyQueryService.findAllBuyBidCoupon(TEST_USER);

// then
assertThat(resultList.size()).isEqualTo(5);
assertThat(resultList.get(0).discountPrice()).isEqualTo(responseDtoList.get(0).discountPrice());
assertThat(resultList.get(0).discountPrice()).isEqualTo(
CouponCalculator.calculateDiscount(TEST_COUPON_FIX, responseDtoList.get(0).discountPrice()));
assertThat(resultList.get(1).discountPrice()).isEqualTo(
CouponCalculator.calculateDiscount(TEST_COUPON_FIX, responseDtoList.get(1).discountPrice()));
assertThat(resultList.get(2).discountPrice()).isEqualTo(responseDtoList.get(2).discountPrice());
assertThat(resultList.get(2).discountPrice()).isEqualTo(
CouponCalculator.calculateDiscount(TEST_COUPON_FIX, responseDtoList.get(2).discountPrice()));
assertThat(resultList.get(3).discountPrice()).isEqualTo(
CouponCalculator.calculateDiscount(TEST_COUPON_FIX, responseDtoList.get(3).discountPrice()));
assertThat(resultList.get(4).discountPrice()).isEqualTo(responseDtoList.get(4).discountPrice());
assertThat(resultList.get(4).discountPrice()).isEqualTo(
CouponCalculator.calculateDiscount(TEST_COUPON_FIX, responseDtoList.get(4).discountPrice()));
}

@Test
void 현재_진행중인_유저의_구매입찰에_쿠폰이_존재하지_않을때_전체_조회_서비스_기능_성공_테스트() {

// given
List<BuyCheckBidResponseDto> responseDtoList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
BuyCheckBidResponseDto responseDto = BuyCheckBidResponseDto.builder()
.buyId((long) i)
.price(1000L * i)
.discountPrice(1000L * i)
.coupon(null)
.build();

responseDtoList.add(responseDto);
}
given(buyRepository.findAllBuyBidCoupon(any(User.class), any(LocalDateTime.class))).willReturn(responseDtoList);

// when
List<BuyCheckBidResponseDto> resultList = buyQueryService.findAllBuyBidCoupon(TEST_USER);

// then
assertThat(resultList.size()).isEqualTo(5);
assertThat(resultList.get(0).discountPrice()).isEqualTo(responseDtoList.get(0).discountPrice());
assertThat(resultList.get(1).discountPrice()).isEqualTo(responseDtoList.get(1).discountPrice());
assertThat(resultList.get(2).discountPrice()).isEqualTo(responseDtoList.get(2).discountPrice());
assertThat(resultList.get(3).discountPrice()).isEqualTo(responseDtoList.get(3).discountPrice());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package bc1.gream.domain.coupon.controller;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import bc1.gream.domain.buy.service.query.BuyQueryService;
import bc1.gream.domain.coupon.entity.Coupon;
import bc1.gream.domain.coupon.service.qeury.CouponQueryService;
import bc1.gream.global.security.UserDetailsImpl;
import bc1.gream.global.security.WithMockCustomUser;
import bc1.gream.test.CouponTest;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@WebMvcTest(controllers = CouponController.class)
@WithMockCustomUser
@ActiveProfiles("test")
class CouponControllerTest implements CouponTest {

@Autowired
protected ObjectMapper objectMapper;
@MockBean
CouponQueryService couponQueryService;
@MockBean
BuyQueryService buyQueryService;
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;

@BeforeEach
void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
.alwaysDo(print()).build();
}

@Test
void 로그인__유저가_사용능한_쿠폰을_조회하는_컨트롤러_기능_성공_테스트() throws Exception {

// given
List<Coupon> couponList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
couponList.add((i % 2 == 0) ? TEST_COUPON_FIX : TEST_COUPON_RATE);
}

given(couponQueryService.availableCouponList(any(UserDetailsImpl.class))).willReturn(couponList);

// when - then
mockMvc.perform(get("/api/coupons"))
.andExpectAll(
status().isOk(),
jsonPath("$.code").value(0),
jsonPath("$.message").value("정상 처리 되었습니다"),
jsonPath("$.data.size()").value(5),
jsonPath("$.data[0].discountType").value("FIX"),
jsonPath("$.data[1].discountType").value("RATE")
);
}

@Test
void 로그인__유저가_이미_사용한_쿠폰을_조회하는_컨트롤러_기능_성공_테스트() throws Exception {

// given
List<Coupon> couponList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
couponList.add((i % 2 == 0) ? TEST_COUPON_RATE_USED : TEST_COUPON_FIX_USED);
}
given(couponQueryService.unavailableCouponList(any(UserDetailsImpl.class))).willReturn(couponList);

// when - then
mockMvc.perform(get("/api/coupons/used"))
.andExpectAll(
status().isOk(),
jsonPath("$.code").value(0),
jsonPath("$.message").value("정상 처리 되었습니다"),
jsonPath("$.data.size()").value(5),
jsonPath("$.data[0].discountType").value("RATE"),
jsonPath("$.data[1].discountType").value("FIX")
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package bc1.gream.domain.coupon.provider;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;

import bc1.gream.domain.admin.dto.request.AdminCreateCouponRequestDto;
import bc1.gream.domain.coupon.entity.Coupon;
import bc1.gream.domain.coupon.entity.DiscountType;
import bc1.gream.domain.coupon.service.command.CouponCommandService;
import bc1.gream.domain.user.entity.User;
import bc1.gream.domain.user.repository.UserRepository;
import bc1.gream.test.CouponTest;
import java.util.Optional;
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;

@ExtendWith(MockitoExtension.class)
class CouponProviderTest implements CouponTest {

@InjectMocks
private CouponProvider couponProvider;
@Mock
private UserRepository userRepository;
@Mock
private CouponCommandService couponCommandService;

@Test
void 관리자가_사용자에게_쿠폰을_등록해주는_Provider_성공_테스트() {

// given
AdminCreateCouponRequestDto requestDto = AdminCreateCouponRequestDto.builder()
.name("TEST COUPON")
.discountType(DiscountType.FIX)
.discount(500L)
.userLoginId(TEST_USER_LOGIN_ID)
.build();

given(userRepository.findByLoginId(any(String.class))).willReturn(Optional.of(TEST_USER));
given(couponCommandService.createCoupon(any(User.class), any(AdminCreateCouponRequestDto.class))).willReturn(TEST_COUPON_FIX);

// when
Coupon resultCoupon = couponProvider.createCoupon(requestDto);

// then
assertThat(resultCoupon.getName()).isEqualTo(requestDto.name());
assertThat(resultCoupon.getDiscount()).isEqualTo(requestDto.discount());
assertThat(resultCoupon.getDiscountType()).isEqualTo(requestDto.discountType());

}
}
Loading

0 comments on commit 5ead75f

Please sign in to comment.