BackEnd/Spring Boot

Spring boot Test Case

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

개발을 하다 보면 Service 기능별 테스트를 해야 할 때가 있다.

그렇다고 테스트 할때마다 서버를 동작시켜 서비스가 실행되는 동작까지 가기에는 은근히 시간을 잡아먹게 된다.

이때 Spring Boot 의 Test 기능을 사용하면 시간이 단축되며 수많은 TestCase를 실행할 수 있다.

한번 간단하게만 사용해 보면 끊을 수 없다.

Spring Boot 테스트 가이드

✅ Import Dependency

testImplementation 'org.springframework.boot:spring-boot-starter-test'
  • JUnit 기반이며 별도로 JUnit import도 가능

✅ 기본 테스트 방법

@SpringBootTest를 사용하면 아래와 같이 properties를 설정할 수 있다.

@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 // 테스트 실행
    void testCase() {
        // 테스트 로직 작성
    }
}

✅ API 테스트 예제

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
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("/api/path") // 실제 경로 입력
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .param("param1", "value"))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();

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

    @Test
    public void getLoginTest(){
        try {
            MvcResult result = mockMvc.perform(post("/api/login")
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .content("{\\"key\\":\\"value\\"}"))
                .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