[Junit TEST 코드] 결과 json 에서 결과 String 받아서 테스트 코드 작성하기

반응형
728x90
반응형

테스트 코드 작성 로그 -1

 

로그인 API

- 테스트 코드를 위한 포스팅으로, 상세 로그인 로직은 생략

package com.api.shop.modules.controller;

import com.api.shop.common.Output;
import com.api.shop.modules.form.LoginForm;
import com.api.shop.modules.form.MemberForm;
import com.api.shop.modules.repository.MemberRepository;
import com.api.shop.modules.service.AuthService;
import com.api.shop.modules.service.MemberService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = {"AuthController"})
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    private final MemberRepository memberRepository;
    private final MemberService memberService;
    private final AuthService authService;
    private final Output output;

    /**
     * 회원가입
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @ModelAttribute MemberForm memberForm) {
        memberService.saveMember(memberForm);
        return output.send();
    }

    /**
     * 로그인
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @ModelAttribute LoginForm loginForm) {
        String memberName = authService.login(loginForm);
        return output.send(memberName);
    }
}

 

 

테스트 코드

  • AuthControllerTest.java
package com.api.shop.modules.controller;

import com.api.shop.config.security.Role;
import com.api.shop.modules.entity.Member;
import com.api.shop.modules.repository.MemberRepository;
import com.jayway.jsonpath.JsonPath;
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.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.util.List;
import java.util.Optional;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
class AuthControllerTest {
    @Autowired
    MockMvc mockMvc;

    @Autowired
    MemberRepository memberRepository;

    @DisplayName("로그인_통과")
    @Test
    void login_통과() throws Exception {
        String requestMemberName = "seohae";

        /* step1. 회원가입 */
        mockMvc.perform(post("/auth/register")
                        .param("memberName", requestMemberName)
                        .param("password", "12341234"))
                .andExpect(status().isOk());

        /* step2. 로그인 */
        MvcResult result = mockMvc.perform(post("/auth/login")
                        .param("memberName", requestMemberName)
                        .param("password", "12341234"))
                .andExpect(status().isOk())
                .andReturn();

        /* get result : login MemberName */
        String response = result.getResponse().getContentAsString();
        String memberName = JsonPath.parse(response).read("$.body");

        /* memberName check */
        Assertions.assertThat(requestMemberName).isEqualTo(memberName);

        /* member 가져와서 Role check */
        Optional<Member> byMemberName = memberRepository.findByMemberName(memberName);
        Assertions.assertThat(byMemberName.get().getRole()).isEqualTo(Role.ROLE_USER);
    }
}

 

1) 회원가입 호출

- 별도로 공통 메서드로 처리하는 것도 좋은 방법인 것 같다. 

@DisplayName("로그인_통과")
    @Test
    void login_통과() throws Exception {
        String requestMemberName = "seohae";

        /* step1. 회원가입 */
        mockMvc.perform(post("/auth/register")
                        .param("memberName", requestMemberName)
                        .param("password", "12341234"))
                .andExpect(status().isOk());
       
        ....
   }
}

 

2) 로그인 호출

@DisplayName("로그인_통과")
    @Test
    void login_통과() throws Exception {
        String requestMemberName = "seohae";

        ....
        
        /* step2. 로그인 */
        MvcResult result = mockMvc.perform(post("/auth/login")
                        .param("memberName", requestMemberName)
                        .param("password", "12341234"))
                .andExpect(status().isOk())
                .andReturn();
       
        ....
   }
}

 

3) response 꺼내기

String response = result.getResponse().getContentAsString();

 

4) body 에 있는 memberName("seohae")를 꺼내기

String memberName = JsonPath.parse(response).read("$.body");

 

5) 요청한 파라미터의 memberName 과 결과값 memberName 이 동일한지 체크

/* memberName check */
Assertions.assertThat(requestMemberName).isEqualTo(memberName);

 

6) memberName(Unique) 으로 회원 정보 조회하여 권한 체크

/* member 가져와서 Role check */
Optional<Member> byMemberName = memberRepository.findByMemberName(memberName);
Assertions.assertThat(byMemberName.get().getRole()).isEqualTo(Role.ROLE_USER);

 

7) 테스트 성공

 

 

반응형

Designed by JB FACTORY