Skip to content

Commit

Permalink
f-lab-edu#30 상품 테스트 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
kimsuyeondev committed May 19, 2024
1 parent 3135e26 commit fe2189e
Show file tree
Hide file tree
Showing 5 changed files with 159 additions and 104 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.cosmetics.goods;

import com.cosmetics.domain.goods.dto.GoodsItemManagement;
import com.cosmetics.domain.goods.dto.GoodsManagement;
import com.cosmetics.domain.goods.dto.GoodsManagementRequest;
import com.cosmetics.domain.goods.dto.GoodsManagementResponse;
import com.cosmetics.domain.goods.dto.item.GoodsItemManagementRequest;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -30,31 +32,31 @@ public class GoodsApiApplicationTest {
@Autowired
private TestRestTemplate testRestTemplate;

private static GoodsManagement requestGoods() {
private static GoodsManagementRequest requestGoods() {
//item
List<GoodsItemManagement> items = new ArrayList<>();
List<GoodsItemManagementRequest> items = new ArrayList<>();

items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("건성용")
.itemQty(50).build());
items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("지성용")
.itemQty(30).build());

return GoodsManagement.builder()
return GoodsManagementRequest.builder()
.category("스킨케어")
.goodsNm("닥터스킨")
.marketPrice(15000)
.salePrice(12000)
.supplyPrice(10000)
.vendorId("lv202400002")
.vendorId(1L)
.stockQty(80)
.brandNm("닥터펫")
.saleStartDtime("2024-05-01 00:00:00")
.saleEndDtime("2024-08-01 00:00:00")
.image("https://cdn.localhost:8081/images/lv202400002/goods/image_1.png")
.addImage("https://cdn.localhost:8081/images/lv202400002/goods/image_2.png")
.item(items)
.items(items)
.build();
}

Expand All @@ -63,8 +65,10 @@ private static GoodsManagement requestGoods() {
@Order(1)
public void 상품등록() throws Exception{
String url = "http://localhost:" + port + "/v1/goods";
GoodsManagement goodsManagement = requestGoods();
ResponseEntity<GoodsManagement> responseEntity = testRestTemplate.postForEntity(url, goodsManagement, GoodsManagement.class);
GoodsManagementRequest goodsManagementRequest = requestGoods();

ResponseEntity<GoodsManagementResponse> responseEntity = testRestTemplate.postForEntity(url, goodsManagementRequest, GoodsManagementResponse.class);

assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertNotNull(responseEntity.getBody().getGoodsNo());
assertThat(responseEntity.getBody().getResultCode()).isEqualTo("0000");
Expand All @@ -75,7 +79,7 @@ private static GoodsManagement requestGoods() {
@Order(2)
public void 상품조회() throws Exception{
String url = "http://localhost:" + port + "/v1/goods/{goodsNo}";
ResponseEntity<GoodsManagement> responseEntity = testRestTemplate.getForEntity(url, GoodsManagement.class,"240501100001");
ResponseEntity<GoodsManagement> responseEntity = testRestTemplate.getForEntity(url, GoodsManagement.class,1L);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody().getGoodsNm()).isEqualTo("닥터스킨");
}
Expand All @@ -85,7 +89,7 @@ private static GoodsManagement requestGoods() {
@Order(3)
public void 상품삭제() throws Exception{
String url = "http://localhost:" + port + "/v1/goods/{goodsNo}";
ResponseEntity<Map> responseEntity = testRestTemplate.exchange(url, HttpMethod.DELETE, null, Map.class, "240501100001");
ResponseEntity<Map> responseEntity = testRestTemplate.exchange(url, HttpMethod.DELETE, null, Map.class, 1L);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody().get("resultCode")).isEqualTo("0000");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import com.cosmetics.api.goods.controller.GoodsController;
import com.cosmetics.domain.exception.custom.CustomException;
import com.cosmetics.domain.exception.error.GoodsErrorManagement;
import com.cosmetics.domain.goods.dto.GoodsItemManagement;
import com.cosmetics.domain.goods.dto.GoodsManagement;
import com.cosmetics.domain.goods.dto.GoodsManagementRequest;
import com.cosmetics.domain.goods.dto.item.GoodsItemManagementRequest;
import com.cosmetics.domain.goods.service.GoodsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -21,6 +21,7 @@
import java.util.ArrayList;
import java.util.List;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
Expand All @@ -29,6 +30,7 @@

/**
* 컨트롤러 단위 테스트
* 들어가면 안되는 필드가 들어갔는지는 어떻게 테스트 할 수 있을까요?
*/
@WebMvcTest(GoodsController.class)
@Slf4j
Expand All @@ -44,7 +46,7 @@ public class GoodsControllerTest2 {
@DisplayName("상품등록 파라미터가 누락되었을 경우_validation handler_MethodArgumentNotValidException 테스트")
public void validGoodsTest() throws Exception {
//given
GoodsManagement goodsManagement = requestValidGoods();
GoodsManagementRequest goodsManagement = requestValidGoods();

//when
ResultActions resultActions = mockMvc.perform(
Expand All @@ -58,31 +60,30 @@ public void validGoodsTest() throws Exception {
resultActions.andExpect(jsonPath("errorMessage").value("유효하지 않는 값입니다"));
resultActions.andExpect(jsonPath("$.fieldErrorList[0].field").value("goodsNm"));
resultActions.andExpect(jsonPath("$.fieldErrorList[0].message").value("must not be blank"));
resultActions.andExpect(jsonPath("$.fieldErrorList[1].field").value("item[0].itemNm"));
resultActions.andExpect(jsonPath("$.fieldErrorList[1].field").value("items[0].itemNm"));
resultActions.andExpect(jsonPath("$.fieldErrorList[1].message").value("must not be blank"));
}

@Test
@DisplayName("상품등록 시 내부오류로 상품등록이 실패했을 경우_커스텀 예외_CustomExceptionHandler 테스트")
public void saveGoodsFailErrorTest() throws Exception {
GoodsManagement goodsManagement = requestGoods();
GoodsManagementRequest goodsManagement = requestGoods();

given(goodsService.save(goodsManagement)).willThrow(new CustomException(GoodsErrorManagement.GOODS_SAVE_ERROR));
//given(goodsService.save(goodsManagement.toServiceDto())).willThrow(new CustomException(GoodsErrorManagement.GOODS_SAVE_ERROR));
given(goodsService.save(any())).willThrow(new CustomException(GoodsErrorManagement.GOODS_SAVE_ERROR));

//when
ResultActions resultActions = mockMvc.perform(
post("http://localhost:8080/v1/goods")
.contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(goodsManagement)));
resultActions.andDo(print()).andExpect(jsonPath("errorCode").value("GOODS_SAVE_ERROR"));

//확인필요 실패 illegalGoodsTest는 되는데 왜 이거는 안되는지 도저히 모르겠습니다
}

@Test
@DisplayName("삭제할 상품번호가 존재하지 않습니다_IllegalArgumentExceptionHandler 테스트 ")
public void illegalGoodsTest() throws Exception {
String goodsNo = "2024050100001";
given(goodsService.deleteGoods(goodsNo)).willThrow(new IllegalArgumentException("존재하지 않는 상품입니다"));
Long goodsNo = 1L;
given(goodsService.deleteByGoodsNo(goodsNo)).willThrow(new IllegalArgumentException("존재하지 않는 상품입니다"));

mockMvc.perform(MockMvcRequestBuilders.delete("http://localhost:8080/v1/goods/{goodsNo}", goodsNo))
.andDo(print())
Expand All @@ -91,59 +92,59 @@ public void illegalGoodsTest() throws Exception {
.andExpect(jsonPath("errorMessage").value("존재하지 않는 상품입니다"));
}

private static GoodsManagement requestGoods() {
private static GoodsManagementRequest requestGoods() {
//item
List<GoodsItemManagement> items = new ArrayList<>();
List<GoodsItemManagementRequest> items = new ArrayList<>();

items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("건성용")
.itemQty(50).build());
items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("지성용")
.itemQty(30).build());

return GoodsManagement.builder()
return GoodsManagementRequest.builder()
.category("스킨케어")
.goodsNm("닥터스킨")
.marketPrice(15000)
.salePrice(12000)
.supplyPrice(10000)
.vendorId("lv202400002")
.vendorId(1L)
.stockQty(80)
.brandNm("닥터펫")
.saleStartDtime("2024-05-01 00:00:00")
.saleEndDtime("2024-08-01 00:00:00")
.image("https://cdn.localhost:8081/images/lv202400002/goods/image_1.png")
.addImage("https://cdn.localhost:8081/images/lv202400002/goods/image_2.png")
.item(items)
.items(items)
.build();
}

private static GoodsManagement requestValidGoods() {
private static GoodsManagementRequest requestValidGoods() {
//item
List<GoodsItemManagement> items = new ArrayList<>();
List<GoodsItemManagementRequest> items = new ArrayList<>();

items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
//.itemNm("건성용")
.itemQty(50).build());
items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("지성용")
.itemQty(30).build());

return GoodsManagement.builder()
return GoodsManagementRequest.builder()
.category("스킨케어")
//.goodsNm("닥터스킨")
.marketPrice(15000)
.salePrice(12000)
.supplyPrice(10000)
.vendorId("lv202400002")
.vendorId(1L)
.stockQty(80)
.brandNm("닥터펫")
.saleStartDtime("2024-05-01 00:00:00")
.saleEndDtime("2024-08-01 00:00:00")
.image("https://cdn.localhost:8081/images/lv202400002/goods/image_1.png")
.addImage("https://cdn.localhost:8081/images/lv202400002/goods/image_2.png")
.item(items)
.items(items)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.cosmetics.goods.controller;

import com.cosmetics.domain.goods.dto.GoodsItemManagement;
import com.cosmetics.domain.exception.custom.CustomException;
import com.cosmetics.domain.goods.dto.GoodsManagement;
import com.cosmetics.domain.goods.dto.GoodsManagementRequest;
import com.cosmetics.domain.goods.dto.item.GoodsItemManagementRequest;
import com.cosmetics.domain.goods.entity.GoodsManagementEntity;
import com.cosmetics.domain.goods.repository.GoodsRepository;
import com.cosmetics.domain.goods.service.GoodsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -19,6 +24,7 @@

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
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;
Expand All @@ -32,6 +38,7 @@

@SpringBootTest
@AutoConfigureMockMvc
@Slf4j
public class GoodsExceptionTest {

@Autowired
Expand All @@ -40,16 +47,13 @@ public class GoodsExceptionTest {
@Autowired
private MockMvc mockMvc;

@MockBean
private GoodsRepository goodsRepository;

@Test
@DisplayName("상품등록 시 내부오류로 상품등록이 실패했을 경우_커스텀 예외_CustomExceptionHandler 테스트")
public void saveGoodsFailErrorTest() throws Exception {
GoodsManagement goodsManagement = requestGoods();

doReturn(null).when(goodsRepository).save(any(GoodsManagement.class));
// Body = {"resultCode":"0000","resultMsg":"등록성공","goodsNo":"240501100001","category":"스킨케어","goodsNm":"닥터스킨","salePrice":12000,"marketPrice":15000,"supplyPrice":10000,"vendorId":"lv202400002","stockQty":80,"brandNm":"닥터펫","saleStartDtime":"2024-05-01 00:00:00","saleEndDtime":"2024-08-01 00:00:00","item":[{"itemNo":null,"itemNm":"건성용","itemQty":50},{"itemNo":null,"itemNm":"지성용","itemQty":30}],"image":"https://cdn.localhost:8081/images/lv202400002/goods/image_1.png","addImage":"https://cdn.localhost:8081/images/lv202400002/goods/image_2.png"}
GoodsManagementRequest goodsManagement = requestGoods();
//테스트실패
//java.lang.NullPointerException: Cannot invoke "com.cosmetics.domain.goods.dto.GoodsManagement.toEntity()" because "goodsManagement" is null
when(goodsService.save(any(GoodsManagement.class))).thenThrow(CustomException.class);

mockMvc.perform(
post("http://localhost:8080/v1/goods")
Expand All @@ -59,31 +63,31 @@ public void saveGoodsFailErrorTest() throws Exception {
.andExpect(jsonPath("errorMessage").value("상품 등록에 실패하였습니다 잠시 후에 시도해 주세요"));
}

private static GoodsManagement requestGoods() {
private static GoodsManagementRequest requestGoods() {
//item
List<GoodsItemManagement> items = new ArrayList<>();
List<GoodsItemManagementRequest> items = new ArrayList<>();

items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("건성용")
.itemQty(50).build());
items.add(GoodsItemManagement.builder()
items.add(GoodsItemManagementRequest.builder()
.itemNm("지성용")
.itemQty(30).build());

return GoodsManagement.builder()
return GoodsManagementRequest.builder()
.category("스킨케어")
.goodsNm("닥터스킨")
.marketPrice(15000)
.salePrice(12000)
.supplyPrice(10000)
.vendorId("lv202400002")
.vendorId(1L)
.stockQty(80)
.brandNm("닥터펫")
.saleStartDtime("2024-05-01 00:00:00")
.saleEndDtime("2024-08-01 00:00:00")
.image("https://cdn.localhost:8081/images/lv202400002/goods/image_1.png")
.addImage("https://cdn.localhost:8081/images/lv202400002/goods/image_2.png")
.item(items)
.items(items)
.build();
}
}
Loading

0 comments on commit fe2189e

Please sign in to comment.