OPEN HYPER STEP
← 목록으로 (Java+Spring)
JAVA · 83 / 99
java
CHAPTER 83 / 99
읽기 약 2
FUNCTION

테스트 컨테이너: Testcontainers


핵심 개념

Docker 기반 DB 테스트 (PostgreSQL/Redis)·@Testcontainers — 실제 DB로 Repository 테스트.

본문

Testcontainers 설정

GRADLE📋 코드 (4줄)
// build.gradle
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:postgresql'
testImplementation 'org.testcontainers:junit-jupiter'

기본 사용

JAVA📋 코드 (33줄)
@SpringBootTest
@Testcontainers
@ActiveProfiles("test")
class UserRepositoryTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired UserRepository userRepository;

    @Test
    void save_and_find() {
        User user = User.builder()
            .email("alice@example.com")
            .name("Alice")
            .build();
        userRepository.save(user);

        Optional<User> found = userRepository.findByEmail("alice@example.com");
        assertTrue(found.isPresent());
        assertEquals("Alice", found.get().getName());
    }
}

Spring Boot 3.1+ ServiceConnection

JAVA📋 코드 (11줄)
// 더 간단 — 자동 연결
@SpringBootTest
@Testcontainers
class UserRepositoryTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");

    // application 설정 자동 주입 — DynamicPropertySource 불필요
}

Redis Container

JAVA📋 코드 (11줄)
@Container
@ServiceConnection(name = "redis")
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
    .withExposedPorts(6379);


@Test
void cache_test() {
    redisTemplate.opsForValue().set("key", "value");
    assertEquals("value", redisTemplate.opsForValue().get("key"));
}

Compose Container — 여러 서비스

JAVA📋 코드 (7줄)
@Container
@ServiceConnection
static ComposeContainer compose = new ComposeContainer(
    new File("src/test/resources/docker-compose-test.yml")
).withExposedService("postgres", 5432)
 .withExposedService("redis", 6379)
 .withExposedService("kafka", 9092);

컨테이너 재사용 — 빠른 테스트

YAML📋 코드 (2줄)
# ~/.testcontainers.properties
testcontainers.reuse.enable=true
JAVA📋 코드 (2줄)
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
    .withReuse(true);  // 테스트 사이에 재사용

다음 챕터

CH.15 "코드 품질: SonarQube + Checkstyle" — 정적 분석.


AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude

무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6

내 Spring 코드의 Testcontainers 부분을 분석해서
실제 DB 테스트 신뢰도와 개선 우선순위를 알려줘.
ChatGPT

무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro

Testcontainers vs 다른 패턴 비교를
실전 사례 5개로 보여주고 H2 vs Testcontainers를 알려줘.
Gemini

무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro

내 코드베이스 전체를 분석해서
Testcontainers 관련 인메모리만 의존 위험 위치를 보고해줘.
Grok

무료: Grok 4.1 / SuperGrok $30/mo

2026년 한국 기업의 Testcontainers 채택률과
한국 CI에서 Docker 활용 트렌드를 솔직히 알려줘.

⭐ 이것만 기억하세요
테스트 컨테이너: Testcontainers 이 3가지만 확실히 잡으세요
1.Testcontainers로 실제 PostgreSQL/Redis/Kafka — H2와 다르게 프로덕션 동작 그대로
2.@ServiceConnection으로 Spring Boot가 자동 설정 + withReuse(true)로 빠른 반복
3.다음 챕터 CH.15에서 SonarQube — 코드 품질 자동 검사


공유하기
진행도 83 / 99