Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you use Testcontainers with Spring Boot for integration testing? इंटीग्रेशन टेस्टिंग के लिए स्प्रिंग बूट के साथ Testcontainers का उपयोग कैसे करें?

Answer

Testcontainers is a library that spins up real, disposable Docker containers (PostgreSQL, Kafka, Redis, etc.) for integration tests, so tests run against the actual database engine and SQL dialect used in production instead of an in-memory substitute like H2 that can behave subtly differently.

A container is declared as a static field annotated with @Container, its connection details are wired into Spring's environment via @DynamicPropertySource (or Spring Boot 3.1+'s @ServiceConnection), and the container starts once before all tests in the class and is torn down afterward, giving high-fidelity, isolated integration tests without needing a shared external database.

@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void configure(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
    }
}

Testcontainers एक लाइब्रेरी है जो इंटीग्रेशन टेस्ट के लिए वास्तविक, डिस्पोज़ेबल Docker कंटेनर्स (PostgreSQL, Kafka, Redis आदि) चलाती है, जिससे टेस्ट वास्तविक डेटाबेस इंजन के विरुद्ध चलते हैं, न कि H2 जैसे इन-मेमोरी विकल्प के विरुद्ध जो सूक्ष्म रूप से अलग व्यवहार कर सकता है।

एक कंटेनर को @Container से एनोटेट स्टैटिक फील्ड के रूप में घोषित किया जाता है, इसके कनेक्शन विवरण @DynamicPropertySource के ज़रिए स्प्रिंग के एनवायरनमेंट में वायर किए जाते हैं, और कंटेनर क्लास के सभी टेस्ट से पहले एक बार शुरू होता है।

@SpringBootTest
@Testcontainers
class OrderRepositoryIT {
    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void configure(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
    }
}

Was this answer clear?