[java] JUnit으로 REST API 테스트하기

이번 포스트에서는 JUnit을 사용하여 REST API를 테스트하는 방법에 대해 알아보겠습니다.

필요한 의존성 추가하기

먼저 프로젝트에 JUnit과 REST API 클라이언트를 사용하기 위한 의존성을 추가해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.7.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Gradle을 사용하는 경우 build.gradle 파일에 다음 의존성을 추가합니다.

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.junit.jupiter:junit-jupiter:5.7.0'
implementation 'org.springframework.boot:spring-boot-starter-web'

의존성을 추가한 후에는 프로젝트를 다시 빌드해야 합니다.

REST API 테스트 작성하기

JUnit을 사용하여 REST API를 테스트하기 위해 다음과 같은 단계를 따릅니다.

  1. @SpringBootTest 어노테이션을 사용하여 테스트할 클래스를 로드합니다.
  2. TestRestTemplate을 사용하여 REST API에 요청을 보냅니다.
  3. 요청에 대한 응답을 검증하여 원하는 결과를 확인합니다.

간단한 예제를 살펴보겠습니다. /api/books 엔드포인트로 GET 요청을 보내고 JSON 형식의 응답을 확인하는 테스트를 작성해보겠습니다.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BookControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testGetAllBooks() throws Exception {
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/api/books", String.class);
        assertThat(response.getStatusCode().value()).isEqualTo(200);
        assertThat(response.getBody()).isNotNull();
        // 필요한 검증을 추가할 수 있습니다.
    }
}

위의 예제에서 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 어노테이션은 임의의 포트로 애플리케이션을 실행하는 것을 의미합니다. @LocalServerPort 어노테이션을 사용하여 포트 번호를 가져올 수 있습니다.

테스트를 실행하려면 해당 테스트 파일을 실행하거나 Maven 또는 Gradle을 사용하여 테스트를 실행하면 됩니다.

결론

JUnit을 사용하여 REST API를 테스트하는 방법에 대해 알아보았습니다. 적절한 테스트 케이스를 작성하여 애플리케이션의 동작을 검증할 수 있습니다. REST API 테스트는 애플리케이션을 안정적으로 유지하고 버그를 방지하는 데 도움이 됩니다. JUnit은 이러한 테스트 작성에 훌륭한 도구입니다.

참고 자료