본문 바로가기
FrameWork/Spring

Spring Boot Test(JUnit 5)

by 태윤2 2021. 8. 18.
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void returnHello() throws Exception {
        String hello = "hello";

        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }

}
  1. @ExtendWith(SpringExtension.class)
    1. 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행
    2. SpringExtension이라는 스프링 실행자를 사용
    3. 스프링 부트 테스트와 JUnit 사이에 연결자 역할
  2. @WebMvcTest
    1. 여러 스프링 테스트 어노테이션 중, Web(Spring MVC)에 집중할 수 있는 어노테이션
    2. 선언할 경우 @Controller, @ContollerAdvice 등을 사용할 수 있음
    3. 단, @Service, @Component, @Repository 등은 사용할 수 없음
    4. 여기서는 컨트롤러만 사용하기 때문에 선언
  3. @Autowired
    1. 스프링이 관리하는 빈(Bean)을 주입
  4. private MockMvc mvc
    1. 웹 API 를 테스트할 때 사용
    2. 스프링 MVC 테스트의 시작점
    3. 이 클래스를 통해 HTTP GET, POST 등에 대한 API 테스트를 할 수 있음
  5. mvc.perform(get("/hello"))
    1. MockMvcRequestBuilders.get()
    2. MockMvc를 통해 /hello 주소로 HTTP GET 요청을 함
    3. 체이닝이 지원되어 아래와 같이 여러 검증 기능을 이어서 선언 가능
  6. .andExpect(status().isOK())
    1. MockMvcResultMatchers.status()
    2. mvc.perform의 결과를 검증
    3. HTTP Header의 Status를 검증
    4. 200,404,500 등의 상태를 검증
    5. Ok는 200 검증
  7. andExpect(content().string(hello))
    1. MockMvcResultMatchers.content()
    2. mvc.perform의 결과를 검증
    3. 응답 본문의 내용을 검증
    4. Controller에서 "hello"를 리턴하기 때문에 이 값이 맞는지 검증
public class HelloResponseDtoTest {

    @Test
    public void lombokTest(){
        //given
        String name = "test";
        int amount = 1000;

        //when
        HelloResponseDto dto = new HelloResponseDto(name, amount);

        //then
        assertThat(dto.getName()).isEqualTo(name);
        assertThat(dto.getAmount()).isEqualTo(amount);
    }
}
  1. assertThat
    1. org.assertj.core.api.Assertions 의 테스트 검증 라이브러리의 검증 메소드
    2. 검증하고 싶은 대상을 메소드 인자로 받음
    3. 메소드 체이닝이 지원되어 isEqualTo와 같이 메소드를 이어서 사용할 수 있음
  2. isEqualTo
    1. assertj의 동등 비교 메소드
    2. assertThat에 있는 값과 isEqualTo의 값을 비교해서 같을 때만 성공
@Test
    public void returnHelloDto() throws Exception {
        String name = "hello";
        int amount = 1000;

        mvc.perform(
                get("/hello/dto")
                        .param("name", name)
                        .param("amount", String.valueOf(amount))

        )
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name",is(name)))
                .andExpect(jsonPath("$.amount", is(amount)));
    }
  1. param
    1. API 테스트할 때 사용될 요청 파라미터를 설정
    2. 단, 값은 String만 허용됨
    3. 그래서 숫자/날짜 등의 데이터도 등록할 때는 문자열로 변경해야만 가능
  2. jsonPath
    1. MockMvcResultMatchers.jsonPath()
    2. $를 기준으로 필드명을 명시
    3. 여기서는 name과 amount를 검증 $.name, $.amoun로 검증

 

  • 참고자료

              스프링 부트와 AWS로 혼자 구현하는 웹 서비스

'FrameWork > Spring' 카테고리의 다른 글

머스테치  (0) 2021.08.21
JPA Auditing으로 생성시간/수정시간 자동화하기  (0) 2021.08.20
등록/수정/조회 API  (0) 2021.08.19
Spring Data JPA  (0) 2021.08.18
Spring Boot Annotations  (0) 2021.08.18