Skip to content

Commit

Permalink
feat::product controller testCode 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
HyunJunSon committed Jan 16, 2024
1 parent 45d60da commit b32d9ec
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 18 deletions.
14 changes: 7 additions & 7 deletions module-api/src/main/java/com/kernel360/member/dto/MemberDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ public static MemberDto from(Member entity) {
);
}

public Member toEntity(MemberDto memberDto) {
public Member toEntity() {
return Member.of(
memberDto.memberNo(),
memberDto.id(),
memberDto.email(),
memberDto.password(),
memberDto.gender(),
memberDto.birthdate()
this.memberNo(),
this.id(),
this.email(),
this.password(),
this.gender(),
this.birthdate()
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ ResponseEntity<ProductDto> findProductById(@PathVariable("id") Long productId) {
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
}

@GetMapping("/products")
@GetMapping("/products/search")
ResponseEntity<List<ProductDto>> findProductByKeyword(@RequestParam("keyword") String keyword){
final List<ProductDto> list = productService.getProductListByKeyword(keyword);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void setup(){
void 상위코드명을_인수로_받는_공통코드_목록_조회() throws Exception {

String pathVariable = "color";
Integer codeNo = 1;
Long codeNo = 1L;
String codeName = "테스트용 코드";
Integer upperNo = null;
String upperName = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public void setup() {
void 로그인() throws Exception {

MemberDto memberDto = MemberDto.of("testID", "testPassword");
MemberDto memberInfo = new MemberDto(1,
MemberDto memberInfo = new MemberDto(1L,
"test01",
"[email protected]",
"",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class MemberTest {

private Integer memberNo;
private Long memberNo;
private String id;
private String email;
private String password;
Expand All @@ -20,7 +20,7 @@ class MemberTest {

@BeforeEach
void 테스트준비() {
memberNo = 1;
memberNo = 1L;
id = "user123";
email = "[email protected]";
password = "password123";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void init() {
/** given **/
MemberDto loginDto = MemberDto.of("test03", "1234qwer");
Member mockLoginEntity = Member.loginMember(loginDto.id(), loginDto.password());
Member mockEntity = Member.of(502, loginDto.id(), "[email protected]", "0eb9de69892882d54516e03e30098354a2e39cea36adab275b6300c737c942fd", null, null);
Member mockEntity = Member.of(502L, loginDto.id(), "[email protected]", "0eb9de69892882d54516e03e30098354a2e39cea36adab275b6300c737c942fd", null, null);
String mockToken = "dummy_token";

/** stub **/
Expand All @@ -105,13 +105,13 @@ public void init() {
void 토큰_발급_저장_테스트() {

/** given **/
Member memberEntity = Member.of(502, "test03", null, null, null, null);
Member memberEntity = Member.of(502L, "test03", null, null, null, null);
String mockToken = "mockToken";
Auth auth = Auth.jwt(null, 502, mockToken);
Auth auth = Auth.jwt(null, 502L, mockToken);

/** stub **/
when(jwt.generateToken(anyString())).thenReturn(mockToken);
when(authRepository.findOneByMemberNo(anyInt())).thenReturn(auth);
when(authRepository.findOneByMemberNo(anyLong())).thenReturn(auth);

/** when **/
String token = jwt.generateToken(memberEntity.getId()); //mockToken return 정상 수행 확인
Expand All @@ -136,7 +136,7 @@ public void init() {

/** given **/
String id = "test01";
Member memberEntity = Member.of(51, "test01", null, null, null, null);
Member memberEntity = Member.of(51L, "test01", null, null, null, null);

/** stub **/
when(memberRepository.findOneById(anyString())).thenReturn(memberEntity);
Expand Down Expand Up @@ -175,7 +175,7 @@ public void init() {

/** given **/
String email = "[email protected]";
Member memberEntity = Member.of(51, "test01", "[email protected]", null, null, null);
Member memberEntity = Member.of(51L, "test01", "[email protected]", null, null, null);

/** stub **/
when(memberRepository.findOneByEmail(anyString())).thenReturn(memberEntity);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package com.kernel360.product.controller;

import com.kernel360.product.dto.ProductDto;
import com.kernel360.product.entity.Product;
import com.kernel360.product.repository.ProductRepository;
import com.kernel360.product.service.ProductService;
import com.navercorp.fixturemonkey.FixtureMonkey;
import com.navercorp.fixturemonkey.api.introspector.*;
import net.jqwik.api.Arbitraries;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(MockitoExtension.class)
@WebMvcTest(ProductController.class)
class ProductControllerTest {

private MockMvc mockMvc;
private FixtureMonkey fixtureMonkey;
@MockBean
private ProductService productService;
@MockBean
private ProductRepository productRepository;

@BeforeEach
void 준비(WebApplicationContext webApplicationContext) {
fixtureMonkey = FixtureMonkey.builder()
.objectIntrospector(new FailoverIntrospector(
Arrays.asList(
FieldReflectionArbitraryIntrospector.INSTANCE,
ConstructorPropertiesArbitraryIntrospector.INSTANCE,
BeanArbitraryIntrospector.INSTANCE,
BuilderArbitraryIntrospector.INSTANCE
)
))
.build();

mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
void 제품목록요청_왔을때_200응답과_리스폰스가_잘반환되는지() throws Exception {
// given
List<Product> products = fixtureMonkey.giveMeBuilder(Product.class)
.sampleList(5);

List<ProductDto> expectedDtos = products.stream()
.map(ProductDto::from)
.collect(Collectors.toList());

//when
when(productService.getProductList()).thenReturn(products);

// then
mockMvc.perform(get("/products"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(5)));

verify(productService, times(1)).getProductList();
}

@Test
void 제품아이디로_제품조회요청이왔을때_200응답과_리스폰스가_잘반환되는지() throws Exception {
// given
Product mockProduct = fixtureMonkey.giveMeBuilder(Product.class)
.set("productId", 1L)
.sample();

when(productService.getProductById(1L)).thenReturn(Optional.of(mockProduct));

// when & then
mockMvc.perform(get("/product/{id}", 1L))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.productName", is(mockProduct.getProductName())))
.andExpect(jsonPath("$.barcode", is(mockProduct.getBarcode())))
.andExpect(jsonPath("$.description", is(mockProduct.getDescription())))
.andExpect(jsonPath("$.declareNo", is(mockProduct.getDeclareNo())))
.andExpect(jsonPath("$.isViolation", is(mockProduct.getIsViolation())))
.andExpect(jsonPath("$.viewCount", is(mockProduct.getViewCount())));

verify(productService).getProductById(1L);

}

@Test
void 키워드로_검색했을때_200코드와_리스폰스가_잘반환되는지() throws Exception {
// given
List<ProductDto> products = new ArrayList<>();
String keyword = "sample";
for (int i = 0; i < 5; i++) {
ProductDto productDto = fixtureMonkey.giveMeBuilder(ProductDto.class)
.set("productName", keyword + i)
.sample();
products.add(productDto);
}

//when
when(productService.getProductListByKeyword(keyword)).thenReturn(products);

//then
mockMvc.perform(get("/products/search").param("keyword", keyword))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(5)));

verify(productService, times(1)).getProductListByKeyword(keyword);

}

}

0 comments on commit b32d9ec

Please sign in to comment.