프로젝트

[SpringBoot test] BaseTest 클래스 사용 가이드

nineDeveloper 2020. 6. 20.
728x90

BaseTest 클래스 사용 가이드

BaseTest 클래스를 extends 해서 테스트 코드를 작성할 수 있는 방법에 대한 가이드

BaseTest

일반적인 Controller 테스트 코드를 작성할때 이 클래스를 상속 받아서 테스트 코드를 작성하면
별도의 어노테이션이나 필요한 객체를 의존받지 않고 상위 클래스로 부터 받아서 바로 사용할 수 있다

BaseTest 는 가장 기본적인 클래스이고 필요에 따라서 별도의 BaseTest 클래스를 만들거나
기본 BaseTest 클래스에 의존 객체를 추가하거나 어노테이션을 추가하여서 테스트 해도 된다

@Transactional

테스트 시 @Transactional 추가하면 테스트 수행 후 자동으로 롤백 처리가 된다
실제 데이터 처리를 유지하고 싶으면 @Transactional 어노테이션을 주석 처리하고 수행하면 된다

package com.iparking.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StopWatch;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.transaction.Transactional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;


/**
 * BASE 테스트 클래스
 * Created by KMS on 06/03/2020.
 */
@SpringBootTest
@AutoConfigureMockMvc
// @RequiredArgsConstructor
@ActiveProfiles("local")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
@Transactional
public class BaseTest {
    protected final MockMvc mockMvc;
    protected final ObjectMapper mapper;
    protected final WebApplicationContext ctx;
    protected StopWatch stopWatch; //개별 테스트 성능 측정용
    protected static StopWatch totalStopWatch; //종합 테스트 성능 측정용

    // 테스트 JWT 데이터
    protected static String jwtData = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbktleSI6IjIxMEJGMDY1LUFDRjMtNEUxQS04QTM4LThFRjQ0Mzg1NTM5QSIsImlkIjoieXNraW0iLCJuYW1lIjoiXHVhZTQwXHVjNzIwXHVjMTFkIiwiZGVwYXJ0bWVudF9jb2RlIjoiMTUwMTIiLCJkZXBhcnRtZW50X25hbWUiOiJcdWM2ZjlcdWQ1MDRcdWI4NjBcdWQyYjhcdWM1ZDRcdWI0ZGNcdWQzMGNcdWQyYjgiLCJlbXBsb3llZV9udW1iZXIiOiIyMDE3MDAyNCIsImVtYWlsIjoieXNraW1AaXBhcmtpbmcuY28ua3IiLCJwb3NpdGlvbl9jb2RlIjoiSjEiLCJwb3NpdGlvbl9uYW1lIjoiXHViOWU0XHViMmM4XHVjODAwIiwiZHV0eV9jb2RlIjoiTDIiLCJkdXR5X25hbWUiOiJcdWQzMDBcdWM2ZDAiLCJ0ZWFtX25hbWUiOm51bGwsInBhdGgiOiIxMDAwfDEwMDAwfDE1MDExfDE1MDEyIiwicGF0aF9uYW1lIjoiXHVkMzBjXHVkMGI5XHVkMDc0XHViNzdjXHVjNmIwXHViNGRjfFImRHxcdWQ1MDRcdWI4NjBcdWQyYjhcdWM1ZDRcdWI0ZGNcdWQzMDB8XHVjNmY5XHVkNTA0XHViODYwXHVkMmI4XHVjNWQ0XHViNGRjXHVkMzBjXHVkMmI4In0.bxBABM7tSoHyxMyfp2P89rQSGS_cWpAqc-1bcGDrbrY";

    public BaseTest(ObjectMapper mapper, WebApplicationContext ctx) {
        this.mapper = mapper;
        this.ctx = ctx;
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx)
                .addFilters(new CharacterEncodingFilter("UTF-8", true))  // 필터 추가
                .alwaysDo(print())
                .build();
    }

    /**
     * 파일 업로드 데이터 생성
     * @param originalFileName 원본파일명
     * @param reqFileName 요청파일명(API에서 받는 이름)
     * @return
     */
    protected static MockMultipartFile getMultipartFile(String originalFileName, String reqFileName) {
        return getMultipartFile(null, originalFileName, reqFileName);
    }
    /**
     * 파일 업로드 데이터 생성
     * @param originalFileName 원본파일명
     * @param reqFileName 요청파일명(API에서 받는 이름)
     * @return
     */
    protected static MockMultipartFile getMultipartFile(String fileMiddlePath, String originalFileName, String reqFileName) {
        Path filePath = Paths.get("src", "test", "resources");
        if(StringUtils.isNotEmpty(fileMiddlePath))
            filePath = Path.of(filePath.toString(), fileMiddlePath);

        filePath = Paths.get(filePath.toString() ,originalFileName);
        // File file = new File(String.valueOf(filePath));

        //        String contentType = "";
        //        String contentType = "image/png";
        //        String contentType = "application/zip";
        byte[] content = null;

        try {
            //            File file = new File(String.valueOf(path));
            content = Files.readAllBytes(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new MockMultipartFile(reqFileName, originalFileName, null, content);
    }
}

BaseFileTest

AWS S3 파일 업로드 다운로드 테스트를 위한 BaseFileTest 클래스
AWS S3 파일 업로드 다운로드 테스트시 해당 클래스를 상속 받아서 테스트 코드를 구현하면 된다

package com.iparking.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.findify.s3mock.S3Mock;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.StopWatch;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

/**
 * BASE 파일 테스트 클래스
 * Created by KMS on 06/03/2020.
 */
@SpringBootTest
@AutoConfigureMockMvc
//@Import(S3MockConfig.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
@ActiveProfiles("local")
// @Transactional
public class BaseFileTest {
    protected MockMvc mockMvc;
    protected final ObjectMapper mapper;
    protected final WebApplicationContext ctx;
    protected final S3Mock s3Mock;
    protected StopWatch stopWatch;
    protected static StopWatch totalStopWatch;

    // 테스트 JWT 데이터
    protected static String jwtData = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbktleSI6IjIxMEJGMDY1LUFDRjMtNEUxQS04QTM4LThFRjQ0Mzg1NTM5QSIsImlkIjoieXNraW0iLCJuYW1lIjoiXHVhZTQwXHVjNzIwXHVjMTFkIiwiZGVwYXJ0bWVudF9jb2RlIjoiMTUwMTIiLCJkZXBhcnRtZW50X25hbWUiOiJcdWM2ZjlcdWQ1MDRcdWI4NjBcdWQyYjhcdWM1ZDRcdWI0ZGNcdWQzMGNcdWQyYjgiLCJlbXBsb3llZV9udW1iZXIiOiIyMDE3MDAyNCIsImVtYWlsIjoieXNraW1AaXBhcmtpbmcuY28ua3IiLCJwb3NpdGlvbl9jb2RlIjoiSjEiLCJwb3NpdGlvbl9uYW1lIjoiXHViOWU0XHViMmM4XHVjODAwIiwiZHV0eV9jb2RlIjoiTDIiLCJkdXR5X25hbWUiOiJcdWQzMDBcdWM2ZDAiLCJ0ZWFtX25hbWUiOm51bGwsInBhdGgiOiIxMDAwfDEwMDAwfDE1MDExfDE1MDEyIiwicGF0aF9uYW1lIjoiXHVkMzBjXHVkMGI5XHVkMDc0XHViNzdjXHVjNmIwXHViNGRjfFImRHxcdWQ1MDRcdWI4NjBcdWQyYjhcdWM1ZDRcdWI0ZGNcdWQzMDB8XHVjNmY5XHVkNTA0XHViODYwXHVkMmI4XHVjNWQ0XHViNGRjXHVkMzBjXHVkMmI4In0.bxBABM7tSoHyxMyfp2P89rQSGS_cWpAqc-1bcGDrbrY";

    protected BaseFileTest(ObjectMapper mapper, WebApplicationContext ctx, S3Mock s3Mock) {
        this.mapper = mapper;
        this.ctx = ctx;
        this.s3Mock = s3Mock;
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx)
                .addFilters(new CharacterEncodingFilter("UTF-8", true))  // 필터 추가
                .alwaysDo(print())
                .build();
    }
}
728x90

댓글

💲 추천 글