YWC

spring ) 단위 테스트 4 본문

공부/Web) Spring

spring ) 단위 테스트 4

YWC 2023. 9. 5. 14:32

2023.09.05 - [공부/Web) Spring] - spring ) 단위 테스트 1

2023.09.05 - [공부/Web) Spring] - spring ) 단위 테스트 2

2023.09.05 - [공부/Web) Spring] - spring ) 단위 테스트 3


1. controller 제작

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

2. Test 파일 제작

3. Test 코드 삽입

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

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

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

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

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

4. 코드 분석

@RunWith(SpringRunner.class)

- 테스트 진행 시 JUnit에 내장된 실행자 외에 다른 실행자 실행

- spring boot 와 JUnit 사이의 연결자 역할

 

@WebMvcTest

- Web(Spring MVC)에 집중

- 선언시 @Controller, @ControllerAdvice 사용가능 (@Service, @Component, @Repository 사용 불가능)

 

@Autowired

- 스프링이 관리하는 Bean 주입

 

@private MockMvc mvc

- 웹 API 테스트시 사용

- 스프링 MVC 테스트의 시작점

- HTTP GET< POST 등 API test 가능

 

@mvc.perform(get("/hello"))

- MockMvc를 통해 /hello 주소로 get 요청

 

.andExpect(status().isOk())

- mvc.perform 의 결과 검증

- Http Header의 Status 검증

- 200, 404, 500 상태 검증

.andExpect(content().string(hello))

- mvc.perform 의 결과 검증

- controller에서 "hello" return 값이 맞는지 검증

 

5. 결과 확인

 

 


[ 참고 자료 ]

https://knowhoon.tistory.com/119

'공부 > Web) Spring' 카테고리의 다른 글

spring ) controller에서 dto 값 받기  (0) 2023.09.06
spring ) 단위 테스트 5  (0) 2023.09.06
spring ) 단위 테스트 1  (0) 2023.09.05
spring ) 단위 테스트 3  (0) 2023.09.05
spring ) 단위 테스트 2  (0) 2023.09.05