पाठ 20 / 25

Integration Tests with Testcontainers

Test against real databases and brokers in containers.

Real dependencies, disposable

Mocks and in-memory databases cannot catch problems in SQL dialects, migrations, transactions, constraints or message serialisation. Testcontainers starts real dependencies, such as PostgreSQL, MySQL, Kafka, RabbitMQ, Redis or LocalStack for AWS services, in Docker containers for the duration of the tests, then removes them. The JUnit 5 integration uses @Testcontainers with @Container fields; static containers are shared across tests in a class. Spring Boot 3.1+ adds @ServiceConnection, which reads a container's connection details and configures the application automatically, so no manual property wiring is needed. Run such tests as integration tests (often named *IT and executed by the Maven Failsafe plugin or a separate Gradle task) so the fast unit suite stays fast. Reuse containers across test classes where possible (singleton container pattern) to save start-up time, and make sure CI agents can run Docker.

A Spring Boot integration test against real PostgreSQL

The container starts once; @ServiceConnection wires the datasource.

@SpringBootTest
@Testcontainers
class CheckoutFlowIT {

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

    @Autowired CheckoutService checkout;
    @Autowired OrderRepository orders;

    @MockitoBean PaymentGateway payments;            // external system mocked; database is real

    @Test
    void paidOrderIsStoredWithItsLines() {
        given(payments.charge(any(), anyLong())).willReturn(PaymentResult.approved("pay_9"));

        Long id = checkout.checkout(cartWith("pen", 2, "notebook", 1));

        PurchaseOrder saved = orders.findWithLines(id).orElseThrow();
        assertThat(saved.status()).isEqualTo(OrderStatus.PAID);
        assertThat(saved.lines()).hasSize(2);
    }
}

// Maven: name integration tests *IT and run them with the failsafe plugin
// mvn verify      (unit tests via surefire, then integration tests via failsafe)

A test kitchen

Testcontainers is a test kitchen with the same ovens as the real restaurant, set up for the tasting and cleared away afterwards. You find out the cake burns in that oven before customers do.

त्वरित जाँच: What does @ServiceConnection do in a Spring Boot test with Testcontainers?

  • It disables the container
  • It mocks the database
  • It runs tests in parallel
  • It automatically configures the application's connection properties from the running container
Answer

It automatically configures the application's connection properties from the running container — @ServiceConnection derives connection details from the container, replacing manual property wiring.