[java] Java Cucumber에서 REST API 테스트 실행하기

Cucumber는 BDD(Behavior-Driven Development) 프레임워크로, 사용자의 기능 요구사항을 기반으로 테스트 코드를 작성하는데 도움을 줍니다. 이번에는 Java Cucumber를 사용하여 REST API 테스트를 실행하는 방법에 대해 알아보겠습니다.

1. 프로젝트 설정

먼저, Cucumber를 사용하기 위해 프로젝트에 Cucumber 관련 종속성을 추가해야 합니다. 이를 위해 Maven을 사용할 경우, pom.xml 파일에 다음 종속성을 추가해주세요.

<dependencies>
    <!-- Cucumber -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>6.8.1</version>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>6.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- REST client library -->
    <!-- Add the necessary dependencies for your REST client library of choice -->
</dependencies>

종속성을 추가한 후, Maven 프로젝트를 업데이트하여 필요한 라이브러리를 다운로드합니다.

2. 테스트 코드 작성

Cucumber는 특정 기능에 대한 시나리오를 기술하는 특별한 언어를 제공합니다. 이 언어를 사용하여 REST API 테스트 시나리오를 작성합니다.

테스트 시나리오를 작성할 수 있는 .feature 파일을 프로젝트의 test/resources 디렉토리에 생성합니다. 예를 들어, api_test.feature 파일을 다음과 같이 작성할 수 있습니다.

Feature: API Test

  Scenario: Get request with valid endpoint
    When I send a GET request to "/api/users"
    Then the response status code should be 200
    And the response body should contain user data

  Scenario: Post request with valid data
    Given the request body is:
      """
      {
        "name": "John Doe",
        "email": "johndoe@example.com"
      }
      """
    When I send a POST request to "/api/users"
    Then the response status code should be 201
    And the response body should contain the created user data

위 예제는 /api/users 엔드포인트에 대한 GET 및 POST 요청을 테스트하는 시나리오입니다.

해당 .feature 파일에 정의된 시나리오를 실행할 수 있는 스텝(Step) 코드를 작성해야 합니다. 이를 위해 StepDefinitions.java 파일을 생성하고 다음과 같은 내용을 작성합니다.

import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

public class StepDefinitions {
    @Given("the request body is:")
    public void setRequestBody(String requestBody) {
        // Set the request body to be used in the POST request
    }

    @When("I send a GET request to {string}")
    public void sendGetRequest(String endpoint) {
        // Send a GET request to the specified endpoint
    }

    @When("I send a POST request to {string}")
    public void sendPostRequest(String endpoint) {
        // Send a POST request to the specified endpoint with the previously set request body
    }

    @Then("the response status code should be {int}")
    public void verifyResponseStatusCode(int expectedStatusCode) {
        // Verify that the response status code matches the expected status code
    }

    @Then("the response body should contain {string}")
    public void verifyResponseBody(String expectedData) {
        // Verify that the response body contains the expected data
    }
}

StepDefinitions 클래스는 시나리오에 정의된 각 단계에 해당하는 메서드를 포함하고 있습니다. 각 메서드 내부에서 실제 REST API 요청을 보내고 응답을 검증합니다.

3. 테스트 실행

이제 테스트를 실행해봅시다. 실행 전에 구현되지 않은 메서드를 완성해야 합니다.

Cucumber는 테스트 실행을 위한 여러 가지 방법을 제공합니다. 가장 간단한 방법은 Maven이 제공하는 테스트 명령을 사용하는 것입니다. Maven 프로젝트 루트 디렉토리에서 다음 명령을 실행합니다.

mvn test

테스트가 실행되면서 요청을 보내고 응답을 검증합니다. 테스트 결과가 출력되며, 테스트의 성공 여부와 세부적인 정보를 확인할 수 있습니다.

마무리

이제 Java Cucumber를 사용하여 REST API 테스트를 실행하는 방법에 대해 알아보았습니다. Cucumber를 이용하면 비즈니스 요구사항과 테스트 사양을 한 자리에서 관리할 수 있습니다. 프로젝트에 적용하여 효율적인 테스트 및 개발 프로세스를 구축해보세요.

참고 자료