ABOUT ME

CS 공부 및 코딩 공부 기록

Today
Yesterday
Total
  • 스프링 부트 HTTP 동작 테스트
    Spring Boot 2021. 9. 9. 21:31
    반응형

    ToyController

    package com.example.toy1.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class ToyController {
    
        @GetMapping("/toy")
        public String getHello() {
            return "hello toy";
        }
    }

     

    ToyControllerTest

    package com.example.toy1.controller;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.boot.web.server.LocalServerPort;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class ToyControllerTest {
    
        @LocalServerPort
        private int port;
    
        @Autowired
        private TestRestTemplate restTemplate;
    
        @Test
        public void isShowHelloToy() throws Exception {
            assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/toy", String.class))
                    .contains("hello toy");
        }
    }

    아주 간단하게 만들어 봤다. RAMDOM_PORT는 임의의 포트로 서버를 시작하여 테스트 환경에서 충돌을 방지한다.

    TestRestTemplate를 사용하면 서버를 구동하여 테스트를 하게 된다. 그러므로 서버를 구동하지 않고 테스트를 하고 싶으면 MockMvc를 이용하면 된다.

     


     

    참고

    https://spring.io/guides/gs/testing-web/

    반응형
Designed by Tistory.