BackEnd/Spring Boot

Spring boot Test Case

Raconer 2023. 4. 15. 19:55
728x90

개발을 하다 보면 Service 기능별 테스트를 해야 할 때가 있다.
그렇다고 테스트 할때마다 서버를 동작시켜 서비스가 실행되는 동작까지 가기에는 은근히 시간을 잡아먹게 된다.
이때 Spring Boot 의 Test 기능을 사용하면 시간이 단축되며 수많은 TestCase를 실행할 수 있다.
한번 간단하게만 사용해 보면 끊을수 없다

Import Dependency

    testImplementation 'org.springframework.boot:spring-boot-starter-test'

위의 Dependency를 추가하면 된다. 기본적으로 Junit의 기능을 사용하며 따로 Junit Import 할 수도 있다.

기본 테스트 방법

지금 작성한 내용 2개만 알아도 기본적인 Service, API 테스트는 쉽게 할 수 있다.

이 외에도 @RunWith 등 다양한 테스트 방법을 통해서 환경설정을 얼마나 세세하게 정의할 수 있다.

SpringBootTest는 하단과 같은 방식으로 properties를 설정할 수 있다.

application.preperties라고 생각하면 된다.

@SpringBootTest(
    properties = {
       "test.path=./src/main/java/com/","file.real.name=test.json"
    }
)

서비스 테스트

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestService {

    @Test // 테스트 실행 build
    void testCase() {

    }

}

Spring Boot의 @Service 부분을 테스트하려면 상단 이미지와 같은 정도만 입력해도 충분히 테스트 가능하다.

testCase()를 빌드하면 Service에 관한 단위 테스트를 실행한다.

API 테스트

// API Post 실행시
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
// API Get 실행시
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
// API Result 출력
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
// API Result Http Status
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

@SpringBootTest
@AutoConfigureMockMvc // 임시 서버
public class TestApIController {

    @Autowired
    MockMvc mockMvc; // 임시 서버

    @Test
    public void getPortfolioListTest(){
        try {
            MvcResult result = mockMvc.perform(get("{1}") // Get 실행
            .contentType(MediaType.APPLICATION_JSON_VALUE) // Content Type
            .param("parma1", "value") // Get Value
            ).andExpect(status().isOk()) // 결과 값이 200 일때
            .andDo(print()) // 결과 값에 대한 상세 내용 전체 출력
            .andReturn(); 

            System.out.println(result.getResponse().getContentAsString()); // 결과 Value 만 출력
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void getLoginTest(){
        try {
            MvcResult result = mockMvc.perform(post("")
            .contentType(MediaType.APPLICATION_JSON_VALUE)
            .content("{key:value}") // body 값
            )
            .andExpect(status().isOk())
            .andDo(print())
            .andReturn(); 

            System.out.println(result.getResponse().getContentAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
728x90

'BackEnd > Spring Boot' 카테고리의 다른 글

AOP란?  (0) 2023.04.15
Spring Boot 개발 중간 정리  (0) 2023.04.15
Spring Request Flow  (0) 2023.04.15
Token JJWT  (0) 2023.04.15
json-simple 사용  (0) 2023.04.15