본문 바로가기

Java/Spring

[Spring] 간단한 API 생성 및 테스트 코드(MockMvc이용) 해보기

반응형

테스트 코드를 하기 위해 간단한 API를 생성해보도록 하겠습니다.

 

⭐︎ Spring 프로젝트를 이미 생성된 상태에서 진행됩니다.

⭐︎ SpringBoot를 통한 어노테이션으로 API 설정을 진행합니다.

 


1. 간단한 API 생성

src/java/.../SimpleController.java

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

@RestController //(1)
public class SimpleController {

    @GetMapping("/helloWorld") //(2)
    public String Hello() {
        return "helloWorld";
    }
    
}

 

 

(1) @RestController

  - 컨트롤러를 JSON을 반환하는 컨트롤러로 만들어 준다.

  - 예전에는 @ResponseBody를 각 메소드마다 선언했던 것을 한번에 사용할 수 있게 해준다.

 

(2) @GetMappling

  - HTTP Method인 Get의 요청을 받는 API를 만들어 준다.

 


2. 간단한 API에 대한 테스트 코드 생성

 

  • src/java/test/.../SimpleControllerTest.java
import org.junit.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.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

@RunWith(SpringRunner.class) //(1)
@WebMvcTest //(2)
public class SimpleControllerTest {
    
    @Autowired //(3)
    private MockMvc mvc; //(4)
    
    @Test
    public void returnHelloWorld() throws Exception {
        String helloWorld = "helloWorld";
        
        mvc.perform(get("/helloWorld")) //(5)
                .andExpect(status().isOk()) //(6)
                .andExpect(content().string(helloWorld)); //(7)
    }
}

 

⭐︎ 일반적으로 테스트 코드에는 대상 클래스 이름 뒤에 Test를 붙입니다.

 

(1) @RunWith

  - 테스트를 진행할때 JUnit에 내장된 실행자 외에 다른 실행자를 실행시킨다.

  - SpringBoot Test와 JUnit 간의 연결자 역할을 한다.

 

(2) @WebMvcTest

  - 이를 선언할 경우 @Controller, @ControllerAdvice 등을 사용할 수 있다.

  - 단, @Service, @Component, @Repository 등은 사용할 수 없다.

  - 여기서는 컨트롤러만 사용하기 때문에 선언한다.

 

(3) @Autowired

  - Spring이 관리하는 Bean을 주입한다.

 

(4) MockMvc

  - 웹 API를 테스트할 때 사용한다.

  - 스프링 MVC 테스트의 시작점으로 이 클래스를 통해 HTTP method등에 대한 API 테스트를 할 수 있다.

 

(5) mvc.perform("/...")

  - MockMvc를 통해 /... 주소로 HTTP GET 요청을 한다.

 

(6) .andExpect(status(). ..)

  - mvc.perform 의 결과를 검증한다.

  - HTTP Header의 Status를 검증한다. → 200, 404, 500등의 HTTP 상태값을 알 수 있다.

  

(7) .andExpect(content(). ..)

 - mvc.perform 의 결과를 검증한다.

 - 응답 본문의 내용을 검증한다.

 


3. 테스트 코드 결과 (console)

성공

테스트 코드 성공 화면

 

실패

테스트 코드 실패 화면

 


4. 테스트 코드를 보면서...

 

테스트 코드가 성공 결과로 확인을 하면, 서버를 구동해서 정상적으로 값이 출력되는지 확인을 해야합니다.

 

- 간단한 API 호출 URL : http://localhost:8080/helloWorld

서버 구동한 후 웹 페이지에서 호출하여 값을 확인

 

브라우저로 한 번씩 검증은 하되, 반드시 테스트 코드는 꼭 따라 해야합니다.

절대로 수동으로 검증하고 테스트 코드를 작성하지 않습니다.

테스트 코드로 먼저 검증 후 정 믿기 힘들때에 프로젝트를 실행해 확인하는 걸 명심하시길 바랍니다.

 

 

 

반응형

❥ CHATI Github