이 레슨에서 배우는 것
- 코드 수정 없이 대상 환경을 바꾸는 설정 만들기
- 태그로 스모크와 전체 테스트를 나눠 실행하기
- CI에서 테스트를 돌리고 Allure·JUnit 리포트 남기기
환경별 설정 분리
대상 서버 주소와 계정은 코드에 두지 않고 실행할 때 주입합니다. 시스템 속성(-D) → 환경 변수 → 기본값 순서로 읽는 작은 설정 클래스면 충분합니다.
public final class Config {
private Config() {}
private static String get(String prop, String env, String def) {
String v = System.getProperty(prop);
if (v == null || v.isBlank()) v = System.getenv(env);
return (v == null || v.isBlank()) ? def : v;
}
public static String baseUrl() { return get("api.baseUrl", "API_BASE_URL", "https://restful-booker.herokuapp.com"); }
public static String username() { return get("api.username", "API_USERNAME", "admin"); }
public static String password() {
String p = get("api.password", "API_PASSWORD", null);
if (p == null) throw new IllegalStateException("API_PASSWORD 환경 변수가 필요합니다");
return p;
}
}API_PASSWORD=password123 mvn test
mvn test -Dapi.baseUrl=https://staging-api.example.com -Dapi.password="$STAGING_PW"Maven Surefire는 mvn에 넘긴 -D 시스템 속성을 테스트 JVM에 그대로 전달합니다. 비밀번호는 기본값을 두지 말고, 없으면 명확한 메시지로 실패하게 하세요.
태그로 스모크와 전체 나누기
@Tag("smoke")
class HealthAndAuthTest extends BookerTestBase { /* ping, 토큰 발급, 핵심 조회 */ }
@Tag("regression")
class BookingValidationTest extends BookerTestBase { /* 파라미터화 케이스 다수 */ }mvn test -Dgroups=smoke # 스모크만
mvn test -DexcludedGroups=slow # 느린 테스트 제외
./gradlew test -PincludeTags=smoke # Gradle은 build.gradle에서 useJUnitPlatform { includeTags ... } 설정test {
useJUnitPlatform {
if (project.hasProperty('includeTags')) includeTags project.property('includeTags')
}
systemProperty 'api.baseUrl', System.getProperty('api.baseUrl')
}병렬 실행
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread
junit.jupiter.execution.parallel.mode.classes.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = 4위 설정은 클래스끼리는 병렬로, 한 클래스 안의 메서드는 순서대로 실행합니다. 병렬 실행이 안전하려면 RestAssured.baseURI 같은 전역 정적 설정을 테스트 중에 바꾸지 말고 스펙을 쓰며, 테스트끼리 데이터를 공유하지 않아야 합니다.
Allure 리포트
JUnit XML은 통과·실패만 보여 줍니다. Allure와 allure-rest-assured 필터를 쓰면 각 테스트에 실제 요청·응답(헤더, 본문)이 첨부된 리포트를 만들 수 있어 실패 분석이 빨라집니다.
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-junit5</artifactId>
<version>2.29.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-rest-assured</artifactId>
<version>2.29.1</version>
<scope>test</scope>
</dependency>.addFilter(new io.qameta.allure.restassured.AllureRestAssured())mvn test # target/allure-results 에 결과 생성
allure serve target/allure-results # Allure CLI로 리포트 열기 (로컬)
allure generate target/allure-results -o target/allure-report --clean # 정적 사이트로결과 폴더 위치는 src/test/resources/allure.properties의 allure.results.directory=target/allure-results로 정합니다. Allure CLI는 별도로 설치하거나 allure-maven 플러그인(mvn allure:report)을 씁니다. 첨부된 요청에도 인증 정보가 들어가니 리포트 공개 범위에 주의하세요. 버전 번호는 예시입니다.
GitHub Actions
name: API tests
on:
pull_request:
push:
branches: [main]
schedule:
- cron: '0 18 * * *' # 매일 03:00 KST 전체 회귀
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- name: Smoke on PR, full regression otherwise
env:
API_PASSWORD: ${{ secrets.BOOKER_PASSWORD }}
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
mvn -B test -Dgroups=smoke
else
mvn -B test
fi
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: test-results
path: |
target/surefire-reports/
target/allure-results/
retention-days: 14테스트가 실패하면 mvn test가 빌드 실패(종료 코드 1)로 끝나 잡이 실패합니다. 실패한 테스트가 있어도 리포트를 만들어야 하는 단계가 뒤에 있다면 -Dmaven.test.failure.ignore=true로 일단 통과시킨 뒤, 리포트 단계에서 결과를 판정하는 방식도 씁니다.
Jenkins
pipeline {
agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
parameters {
choice(name: 'TARGET', choices: ['staging', 'demo'], description: '대상 환경')
}
environment {
API_PASSWORD = credentials('booker-password')
}
stages {
stage('API tests') {
steps {
script {
def urls = [staging: 'https://staging-api.example.com', demo: 'https://restful-booker.herokuapp.com']
sh "mvn -B test -Dapi.baseUrl=${urls[params.TARGET]}"
}
}
}
}
post {
always {
junit 'target/surefire-reports/*.xml'
// Allure Jenkins 플러그인이 있다면: allure results: [[path: 'target/allure-results']]
}
}
}한 걸음 더: 계약 테스트
REST Assured 테스트는 "배포된 API가 기대대로 동작하는가"를 확인합니다. 여러 팀이 API를 주고받는 마이크로서비스 환경에서는 소비자가 기대하는 계약을 제공자 빌드에서 검증하는 소비자 주도 계약 테스트(Pact, Spring Cloud Contract)를 함께 쓰면, 통합 환경에 배포하기 전에 호환성 문제를 잡을 수 있습니다. Spring Cloud Contract는 생성되는 테스트에 REST Assured를 사용합니다.
정리
- 대상 서버·계정은
-D시스템 속성이나 환경 변수로 주입하고, 비밀값에는 기본값을 두지 않습니다. @Tag로 스모크·회귀를 나눠 PR에는 스모크, 머지·야간에는 전체를 실행합니다.- 병렬 실행은
junit-platform.properties로 켜고, 전역 상태와 데이터 공유를 피합니다. allure-rest-assured필터로 요청·응답이 첨부된 리포트를 만들고, JUnit XML은 CI 화면에 연동합니다.