이 레슨에서 배우는 것
- Maven·Gradle 프로젝트에 REST Assured 추가하기
- given/when/then으로 첫 테스트 작성하고 실행하기
- 실패 메시지와 요청·응답 로그로 원인 찾기
프로젝트 설정
JDK 17 이상을 설치하고 Maven 프로젝트를 만듭니다. 테스트 코드는 src/test/java에 둡니다.
pom.xml (일부)xml
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.13.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.3</version>
</plugin>
</plugins>
</build>build.gradle (Gradle을 쓴다면)groovy
dependencies {
testImplementation 'io.rest-assured:rest-assured:5.5.6'
testImplementation 'org.junit.jupiter:junit-jupiter:5.13.4'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
test {
useJUnitPlatform()
}버전 번호는 예시입니다. Maven Central에서 최신 버전을 확인하세요. Hamcrest는 REST Assured가 함께 가져오므로 따로 추가하지 않아도 됩니다.
첫 테스트
src/test/java/booking/PingTest.javajava
package booking;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
class PingTest {
@BeforeAll
static void setUp() {
RestAssured.baseURI = "https://restful-booker.herokuapp.com";
}
@Test
void 서버가_살아있다() {
when()
.get("/ping")
.then()
.statusCode(201); // 이 연습용 API는 ping에 201을 돌려준다
}
@Test
void 예약_한_건을_조회한다() {
given()
.accept("application/json")
.pathParam("id", 1)
.when()
.get("/booking/{id}")
.then()
.statusCode(200)
.contentType("application/json")
.body("firstname", not(emptyOrNullString()))
.body("bookingdates.checkin", matchesPattern("\\d{4}-\\d{2}-\\d{2}"));
}
}import static io.restassured.RestAssured.*로given()·when()을,org.hamcrest.Matchers.*로equalTo·hasItems같은 매처를 바로 씁니다.given()은 생략할 수 있습니다. 준비할 것이 없으면when()부터 시작합니다.body("경로", 매처)의 경로는 JSON 응답 안의 위치입니다(GPath, 3강).- JUnit 5는 한글 메서드 이름을 허용합니다. 리포트에서 읽기 쉬운 이름을 쓰거나
@DisplayName을 붙이세요.
POST 요청
java
@Test
void 예약을_만든다() {
String body = """
{
"firstname": "Jim",
"lastname": "Brown",
"totalprice": 111,
"depositpaid": true,
"bookingdates": { "checkin": "2026-12-01", "checkout": "2026-12-03" },
"additionalneeds": "Breakfast"
}
""";
int bookingId =
given()
.contentType("application/json")
.accept("application/json")
.body(body)
.when()
.post("/booking")
.then()
.statusCode(200)
.body("bookingid", greaterThan(0))
.body("booking.firstname", equalTo("Jim"))
.body("booking.bookingdates.checkout", equalTo("2026-12-03"))
.extract()
.path("bookingid");
System.out.println("생성된 예약: " + bookingId);
}Java 15 이상의 텍스트 블록(""")으로 JSON을 그대로 붙여 넣을 수 있습니다. 실무에서는 문자열보다 객체를 직렬화하는 방식(4강)이 유지보수에 좋습니다. extract().path()로 응답 값을 꺼내 다음 단계에 쓸 수 있습니다.
실행
bash
mvn test # 전체
mvn test -Dtest=PingTest # 클래스 하나
mvn test -Dtest='PingTest#서버가_살아있다' # 메서드 하나
./gradlew test --tests booking.PingTest # GradleIntelliJ IDEA에서는 클래스·메서드 옆의 ▶ 버튼으로 바로 실행하고 디버거를 붙일 수 있습니다. 결과는 target/surefire-reports/에 JUnit XML로 저장됩니다.
실패 메시지와 로그
검증 실패 예text
java.lang.AssertionError: 1 expectation failed.
JSON path booking.firstname doesn't match.
Expected: "Jim"
Actual: "jim"무엇이 왜 실패했는지 보려면 요청과 응답 로그를 켭니다.
java
given()
.log().all() // 보낸 요청 전체 (메서드, URL, 헤더, 본문)
.when()
.get("/booking/1")
.then()
.log().ifValidationFails() // 검증이 실패했을 때만 응답 출력
.statusCode(200);
// 모든 테스트에 적용: 실패한 경우에만 요청과 응답을 함께 출력
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();log().all() 대신 log().body(), log().headers(), log().uri()로 일부만 볼 수도 있습니다. 로그에는 인증 헤더가 그대로 찍히니 CI 로그 공개 범위에 주의하세요(5강의 헤더 가리기 참고).
정리
rest-assured와junit-jupiter를 테스트 의존성으로 추가하고 static import로 문법을 간결하게 씁니다.given()(헤더·파라미터·본문) →when()(메서드·경로) →then()(상태·본문 검증) 순서로 씁니다.extract()로 응답 값을 꺼내고,log().ifValidationFails()로 실패 원인을 확인합니다.