[java] TestContainers에서 사용 가능한 다른 컨테이너 제공자

TestContainers는 자바 개발자들이 통합 테스트를 수행할 때 도커 컨테이너를 쉽게 사용할 수 있게 도와주는 도구입니다. 이를 통해 테스트 환경을 미리 설정하고, 테스트 메서드를 실행할 때마다 새로운 컨테이너를 시작하여 테스트를 수행할 수 있습니다.

TestContainers는 다양한 컨테이너 제공자를 지원합니다. 여기서는 TestContainers에서 제공하는 다른 컨테이너 제공자를 살펴보겠습니다.

1. PostgreSQLContainer

PostgreSQLContainer는 PostgreSQL 데이터베이스를 사용할 수 있도록 도커 컨테이너를 시작합니다. 이를 통해 테스트 환경에서 실제 데이터베이스를 사용하여 테스트를 수행할 수 있습니다.

사용 예시:

import org.testcontainers.containers.PostgreSQLContainer;

public class MyPostgreSQLTest {

    static final PostgreSQLContainer<?> postgreSQLContainer =
        new PostgreSQLContainer<>("postgres:13.3")
            .withDatabaseName("mytestdb")
            .withUsername("mytestuser")
            .withPassword("mytestpassword");

    @BeforeAll
    static void setUp() {
        postgreSQLContainer.start();
    }

    @AfterAll
    static void tearDown() {
        postgreSQLContainer.stop();
    }

    @Test
    void testDatabaseConnection() {
        // 테스트 코드 작성
    }

}

2. MySQLContainer

MySQLContainer는 MySQL 데이터베이스를 사용할 수 있도록 도커 컨테이너를 시작합니다. PostgreSQLContainer와 마찬가지로 테스트 환경에서 실제 데이터베이스를 사용하여 테스트를 수행할 수 있습니다.

사용 예시:

import org.testcontainers.containers.MySQLContainer;

public class MyMySQLTest {

    static final MySQLContainer<?> mySQLContainer =
        new MySQLContainer<>("mysql:8.0.26")
            .withDatabaseName("mytestdb")
            .withUsername("mytestuser")
            .withPassword("mytestpassword");

    @BeforeAll
    static void setUp() {
        mySQLContainer.start();
    }

    @AfterAll
    static void tearDown() {
        mySQLContainer.stop();
    }

    @Test
    void testDatabaseConnection() {
        // 테스트 코드 작성
    }

}

3. RedisContainer

RedisContainer는 Redis 서버를 사용할 수 있도록 도커 컨테이너를 시작합니다. 이를 통해 테스트 환경에서 실제 Redis 서버를 사용하여 테스트를 수행할 수 있습니다.

사용 예시:

import org.testcontainers.containers.GenericContainer;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;

public class MyRedisTest {

    static final GenericContainer<?> redisContainer =
        new GenericContainer<>("redis:6.2.5");

    @BeforeAll
    static void setUp() {
        redisContainer.start();
    }

    @AfterAll
    static void tearDown() {
        redisContainer.stop();
    }

    @Test
    void testRedisConnection() {
        RedisClient redisClient = RedisClient.create(redisContainer.getRedisURI());
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        
        // 테스트 코드 작성
        
        connection.close();
        redisClient.shutdown();
    }

}

결론

위에서 언급한 세 가지 컨테이너 제공자는 TestContainers에서 제공하는 일부 다양한 컨테이너 제공자들입니다. 이를 통해 테스트 환경에서 실제 서비스와 유사한 환경을 구성하여 통합 테스트를 수행할 수 있습니다.