Testcontainers with Spring Boot: Real Database Integration Tests

Testcontainers with Spring Boot: Real Database Integration Tests

Testcontainers spins up real Docker containers — PostgreSQL, MySQL, Redis, Kafka — inside your JUnit tests. With Spring Boot's @DynamicPropertySource and ServiceConnection support, the wiring is minimal and the confidence level is high.

Key Takeaways

Testcontainers runs real Docker images in your test process. No mocks, no in-memory approximations — the same database engine your production app talks to.

@DynamicPropertySource wires container URLs into the Spring context. It runs before the context is created, so properties are available to all auto-configurations.

Reusable containers cut startup cost by 90%. With .withReuse(true) and the testcontainers.reuse.enable flag, the same container instance persists across test runs.

Spring Boot 3.1+ adds @ServiceConnection. A single annotation replaces manual @DynamicPropertySource wiring for supported container types.

Use a shared base class for multi-container setups. Declaring containers as static fields on an abstract base class ensures one container instance serves all test classes.

H2 in-memory databases are convenient, but they lie. PostgreSQL's jsonb operators, MySQL's FULLTEXT indexes, and Flyway migrations using database-specific DDL all behave differently on H2. Testcontainers fixes this by running the exact same database engine your production app uses — inside Docker, managed by JUnit.

Setup

Add the dependencies:

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <scope>test</scope>
</dependency>

<!-- BOM to manage versions -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers-bom</artifactId>
            <version>1.19.7</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Also disable H2 auto-configuration when using a real database:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Basic PostgreSQL Test

@SpringBootTest
@Testcontainers
class OrderRepositoryTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-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
    private OrderRepository orderRepository;

    @Test
    void shouldSaveAndRetrieveOrder() {
        Order order = new Order("customer-1", OrderStatus.PENDING);
        order.addItem("product-A", 2, BigDecimal.valueOf(9.99));

        Order saved = orderRepository.save(order);

        assertThat(saved.getId()).isNotNull();
        assertThat(saved.getItems()).hasSize(1);
    }
}

The static keyword on @Container is important — it means the container starts once per test class, not once per test method.

Spring Boot 3.1+: @ServiceConnection

Spring Boot 3.1 introduced @ServiceConnection, which eliminates manual @DynamicPropertySource wiring for supported containers:

@SpringBootTest
@Testcontainers
class OrderRepositoryTest {

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

    // No @DynamicPropertySource needed — Spring Boot reads connection details from the container
    @Autowired
    private OrderRepository orderRepository;

    @Test
    void shouldPersistOrder() { ... }
}

@ServiceConnection works for PostgreSQL, MySQL, MongoDB, Redis, RabbitMQ, Kafka, and more. Check the Spring Boot docs for the full list.

Testing with MySQL

@SpringBootTest
@Testcontainers
class ProductCatalogTest {

    @Container
    @ServiceConnection
    static MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.0")
        .withDatabaseName("catalog")
        .withUsername("test")
        .withPassword("test");

    @Autowired
    private ProductRepository productRepository;

    @Test
    void shouldUseFullTextSearch() {
        productRepository.save(new Product("Blue Widget Pro", "electronics"));
        productRepository.save(new Product("Red Widget Lite", "electronics"));
        productRepository.save(new Product("Green Book", "media"));

        // MySQL FULLTEXT index query
        List<Product> results = productRepository.fullTextSearch("widget");

        assertThat(results).hasSize(2)
            .extracting(Product::getName)
            .allMatch(name -> name.toLowerCase().contains("widget"));
    }
}

Testing with Redis

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <scope>test</scope>
</dependency>
@SpringBootTest
@Testcontainers
class ProductCacheTest {

    @Container
    @ServiceConnection
    static RedisContainer redis = new RedisContainer("redis:7-alpine");

    @Autowired
    private ProductCacheService cacheService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void shouldCacheProductLookup() {
        Product product = new Product(1L, "Widget", BigDecimal.valueOf(9.99));

        cacheService.cacheProduct(product);

        String cached = redisTemplate.opsForValue().get("product:1");
        assertThat(cached).isNotNull();
        assertThat(cached).contains("Widget");
    }
}

Reusable Containers

Starting a Docker container takes 2-10 seconds. Across a test suite with 50 test classes, that's minutes of startup overhead. Reusable containers fix this:

1. Enable reuse globally:

# ~/.testcontainers.properties
testcontainers.reuse.enable=true

2. Mark containers for reuse:

static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine")
    .withDatabaseName("testdb")
    .withUsername("test")
    .withPassword("test")
    .withReuse(true);

With reuse enabled, Testcontainers computes a hash of the container configuration. If a running container matches that hash, it's reused. Your test suite goes from "start N containers" to "start 1 container, reuse it everywhere."

Important caveat: With reuse, data from previous test runs persists. Use @Transactional on test classes, or truncate tables in @BeforeEach:

@BeforeEach
void cleanDatabase(@Autowired JdbcTemplate jdbcTemplate) {
    jdbcTemplate.execute("TRUNCATE TABLE orders, order_items, products CASCADE");
}

Shared Base Class Pattern

The cleanest way to manage containers across a large test suite:

// src/test/java/com/example/IntegrationTestBase.java
@SpringBootTest
@Testcontainers
public abstract class IntegrationTestBase {

    @Container
    static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:15-alpine")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test")
        .withReuse(true);

    @Container
    static final GenericContainer<?> REDIS = new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379)
        .withReuse(true);

    @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);
        registry.add("spring.data.redis.host", REDIS::getHost);
        registry.add("spring.data.redis.port", () -> REDIS.getMappedPort(6379));
    }
}

// Usage:
class OrderServiceTest extends IntegrationTestBase {
    @Autowired private OrderService orderService;

    @Test
    void shouldCreateOrder() { ... }
}

class ProductCacheTest extends IntegrationTestBase {
    @Autowired private ProductCacheService cacheService;

    @Test
    void shouldCacheProduct() { ... }
}

Both test classes share the same containers — Spring's context caching ensures they also share the same ApplicationContext.

Testing Flyway Migrations

@SpringBootTest
@Testcontainers
class FlywayMigrationTest {

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    void shouldApplyAllMigrations() {
        // If we got here, Flyway ran successfully at startup
        // Verify expected schema exists
        Integer tableCount = jdbcTemplate.queryForObject(
            "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'",
            Integer.class
        );
        assertThat(tableCount).isGreaterThan(5);
    }

    @Test
    void shouldHaveExpectedColumns() {
        List<String> columns = jdbcTemplate.queryForList(
            "SELECT column_name FROM information_schema.columns WHERE table_name = 'orders'",
            String.class
        );
        assertThat(columns).contains("id", "customer_id", "status", "created_at", "updated_at");
    }
}

Testing Kafka with Testcontainers

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>kafka</artifactId>
    <scope>test</scope>
</dependency>
@SpringBootTest
@Testcontainers
class OrderEventPublisherTest {

    @Container
    @ServiceConnection
    static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.4.0"));

    @Autowired
    private OrderEventPublisher publisher;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Test
    void shouldPublishOrderCreatedEvent() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        AtomicReference<String> received = new AtomicReference<>();

        // Set up consumer
        kafkaTemplate.receive("order-events", 0, 0);

        Order order = new Order("customer-1");
        publisher.publishOrderCreated(order);

        assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
        assertThat(received.get()).contains("order.created");
    }
}

Testing Application Startup with Testcontainers

A test that verifies the entire application starts correctly against a real database is one of the highest-value integration tests you can write:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class ApplicationStartupTest {

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

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void shouldStartAndRespondToHealthCheck() {
        ResponseEntity<String> response = restTemplate.getForEntity(
            "http://localhost:" + port + "/actuator/health",
            String.class
        );

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).contains("\"status\":\"UP\"");
    }
}

Performance Tips

Tip 1: Use Alpine images

postgres:15-alpine is ~100MB vs ~400MB for the full image. Faster pull on CI.

Tip 2: Disable Ryuk on CI

Ryuk is the Testcontainers resource reaper. On some CI environments it causes issues:

TESTCONTAINERS_RYUK_DISABLED=true

Tip 3: Use fixed container names for reuse

.withLabel("reuse.hash", "my-fixed-hash")

Tip 4: Profile container startup with logging

postgres.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("postgres")));

CI Configuration

On GitHub Actions:

services:
  # Optional: pre-pull images to speed up first run
  docker:
    image: docker:dind

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
      - name: Run tests
        run: ./mvnw test
        env:
          TESTCONTAINERS_RYUK_DISABLED: true

Docker is available on GitHub Actions runners by default — no additional configuration needed.

Combining with End-to-End Testing

Testcontainers covers the backend integration layer thoroughly. For full end-to-end testing — UI flows, multi-service scenarios, and user-journey validation — tools like HelpMeTest complement your Testcontainers suite by testing the running application from the outside, catching issues that JUnit-level tests can't see.

Summary

Testcontainers brings your integration tests as close to production as possible without requiring a dedicated test environment. Start with @ServiceConnection for zero-boilerplate wiring in Spring Boot 3.1+, use static containers and the shared base class pattern to minimize startup cost, and enable reuse for local development. The result is a test suite that catches real database issues before they reach production.

Read more

Start now free