Skip to main content

Testing Spring Boot with Testcontainers: Integration Testing with Real Databases

Complete guide to Testcontainers for Spring Boot integration testing. Real PostgreSQL and Redis containers, @DynamicPropertySource, container reuse…

What do you think about this article?

Testing Spring Boot with Testcontainers: Integration Testing with Real Databases
Clean ArchitecturePhotos:RDNE Stock projectPexels

At a Glance

Complete guide to Testcontainers for Spring Boot integration testing. Real PostgreSQL and Redis containers, @DynamicPropertySource, container reuse…

Testcontainers provides real databases (PostgreSQL, Redis, MySQL) in Docker containers during testing, eliminating the need for mocks and stubs for integration testing. With @DynamicPropertySource, Spring Boot automatically loads the container's port and credentials, enabling deterministic testing on real databases without complicated manual setup. This article shows 4 production-ready patterns for Testcontainers in Clean Architecture, with CI/CD best practices.

Introduction: The Problem with Mock Databases

In 2024-2026, many Spring Boot teams write integration tests with in-memory H2 databases or full mocks, but the reality is this: the test passes locally with H2, then in production PostgreSQL fails due to slightly different SQL dialect, deadlock, or different transactional behavior.

Testcontainers solves the problem: every test runs on a real database (PostgreSQL 16, Redis 7) in a Docker container, guaranteeing perfect parity between test and production environments. In Federico Calò's portfolio backend (~175 Flyway migrations, 98+ endpoints), all integration tests use Testcontainers with real PostgreSQL and Redis.

Target: Java developers with 5+ years of experience, who want to elevate test quality from mock-based to database-real, while maintaining execution speed through container reuse across tests.

What is Testcontainers?

Testcontainers is a Java library that starts Docker containers during test execution. Lifecycle:

  1. @Test start: Testcontainers starts a PostgreSQL container (or Redis/MySQL/etc.)
  2. @DynamicPropertySource: Reads port and credentials from the container, injects them into Spring Boot DataSource
  3. Test execution: The test runs against the real database inside the container
  4. @Test end: Container stops and is removed

The big advantage: no manual database configuration, no hardcoding of port 5432. Every developer, every CI/CD pipeline, has an isolated and reproducible database.

Setup: Maven Dependency and Configuration

Add dependencies to pom.xml:


<properties>
    <testcontainers.version>1.20.3</testcontainers.version>
</properties>

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <version>${testcontainers.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <version>${testcontainers.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>${testcontainers.version}</version>
    <scope>test</scope>
</dependency>

<!-- For Redis tests (optional) -->
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>containers</artifactId>
    <version>${testcontainers.version}</version>
    <scope>test</scope>
</dependency>

<!-- PostgreSQL driver -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.7.3</version>
</dependency>

<!-- Spring Boot Test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  

Pattern 1: @SpringBootTest with PostgreSQL Container

Integration test that starts the full Spring context with a real database:


@SpringBootTest
class RegisterUserUseCaseIntegrationTest {

    // 1. Static PostgreSQL container (shared across all tests in the class)
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
        .withDatabaseName("testdb")
        .withUsername("testuser")
        .withPassword("testpass");

    @Autowired
    private RegisterUserUseCase registerUseCase;

    @Autowired
    private UserRepository userRepository;

    // 2. Dynamically inject container properties into Spring Boot
    @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.jpa.hibernate.ddl-auto", () -> "validate");
        registry.add("spring.flyway.enabled", () -> "true");
    }

    // 3. Test: register user and verify persistence
    @Test
    void testRegisterUserAndPersist() {
        RegisterUserRequest request = new RegisterUserRequest(
            "newuser@example.com",
            "SecurePassword123!"
        );

        RegisterUserResponse response = registerUseCase.execute(request);

        // Verify that user is saved in the real database
        Optional<User> savedUser = userRepository.findByEmail(
            new Email(request.email())
        );
        assertTrue(savedUser.isPresent());
        assertEquals(request.email(), savedUser.get().email().value());
    }

    // 4. Test: duplicate email must throw exception
    @Test
    void testRegisterDuplicateEmailThrowsException() {
        Email email = new Email("test@example.com");
        User existingUser = User.register(email, BCrypt.hashpw("pwd", BCrypt.gensalt()));
        userRepository.save(existingUser);

        RegisterUserRequest request = new RegisterUserRequest(
            "test@example.com",
            "NewPassword123!"
        );

        assertThrows(UserAlreadyExistsException.class,
            () -> registerUseCase.execute(request)
        );
    }
}
  

What happens: @SpringBootTest loads the full Spring Boot context, @DynamicPropertySource reads from the container, and Flyway automatically migrates the schema into the test database. No manual setup.

Pattern 2: @DataJpaTest for Persistence Layer Testing

If you want to test only persistence (JPA, repository) without the full context:


@DataJpaTest
@Import({UserJpaAdapter.class, UserJpaMapper.class})  // Adapter to test
class UserJpaAdapterIntegrationTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
        .withDatabaseName("testdb")
        .withUsername("testuser")
        .withPassword("testpass");

    @Autowired
    private UserJpaAdapter userAdapter;

    @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);
    }

    @Test
    void testFindByEmailRetrievesPersistedUser() {
        // 1. Setup: create and persist via adapter
        Email email = new Email("user@example.com");
        User user = User.register(email, BCrypt.hashpw("pwd", BCrypt.gensalt()));
        User saved = userAdapter.save(user);

        // 2. Retrieve and assert
        Optional<User> retrieved = userAdapter.findByEmail(email);

        assertTrue(retrieved.isPresent());
        assertEquals(saved.id(), retrieved.get().id());
    }

    @Test
    void testSaveGeneratesId() {
        Email email = new Email("newuser@example.com");
        User user = User.register(email, BCrypt.hashpw("pwd", BCrypt.gensalt()));

        User saved = userAdapter.save(user);

        assertNotNull(saved.id());
        assertEquals(email, saved.email());
    }
}
  

Advantage: @DataJpaTest is lighter than @SpringBootTest (starts only data layer, not HTTP), faster, but still on a real database.

Pattern 3: Container Lifecycle - Reuse Across Tests

If every test creates a new container, tests become slow (60+ seconds for 10 tests). The solution is to share the container:


@SpringBootTest
class SharedContainerIntegrationTest {

    // Static container: shared across all tests in the class
    // Starts once at the beginning of the class, stops at the end
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
        .withDatabaseName("testdb")
        .withUsername("testuser")
        .withPassword("testpass");

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @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);
    }

    @Test
    void testUser1() {
        // Uses the shared container
        User user = User.register(new Email("user1@example.com"), "hash1");
        userRepository.save(user);
        assertTrue(userRepository.findByEmail(new Email("user1@example.com")).isPresent());
    }

    @Test
    void testUser2() {
        // Same container
        User user = User.register(new Email("user2@example.com"), "hash2");
        userRepository.save(user);
        assertTrue(userRepository.findByEmail(new Email("user2@example.com")).isPresent());
    }

    // Both tests run on the SAME container: time ~3-5s total, not 20s
}
  

Caution: if a test modifies data (INSERT/UPDATE), the data remains in the container for the next test. For isolation, use @Transactional or @Rollback:


@Test
@Transactional  // Automatic rollback after test
void testRegisterAndRollback() {
    User user = User.register(new Email("temp@example.com"), "hash");
    userRepository.save(user);
    assertTrue(userRepository.findByEmail(new Email("temp@example.com")).isPresent());
    // After test: rollback, user is deleted from container
}
  

Pattern 4: @Nested Tests for Organization

With many tests, a class becomes chaotic. Organize with @Nested:


@SpringBootTest
class UserRepositoryIntegrationTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
        .withDatabaseName("testdb")
        .withUsername("testuser")
        .withPassword("testpass");

    @Autowired
    private UserRepository userRepository;

    @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);
    }

    @Nested
    @DisplayName("User Save Operations")
    class SaveTests {
        @Test
        void testSaveNewUser() {
            User user = User.register(new Email("new@example.com"), "hash");
            User saved = userRepository.save(user);
            assertNotNull(saved.id());
        }

        @Test
        void testSaveWithoutEmailThrowsException() {
            assertThrows(Exception.class,
                () -> userRepository.save(new User(null, null, null, null, null, null))
            );
        }
    }

    @Nested
    @DisplayName("User Find Operations")
    class FindTests {
        @Test
        @Transactional
        void testFindByEmailReturnsUser() {
            User user = User.register(new Email("find@example.com"), "hash");
            userRepository.save(user);

            Optional<User> found = userRepository.findByEmail(new Email("find@example.com"));
            assertTrue(found.isPresent());
        }

        @Test
        void testFindNonExistentReturnsEmpty() {
            Optional<User> found = userRepository.findByEmail(new Email("nonexistent@example.com"));
            assertTrue(found.isEmpty());
        }
    }
}
  

Testing Infrastructure Layer in Clean Architecture

In the context of Clean Architecture (domain → application → infrastructure → presentation), Testcontainers excels at testing the infrastructure layer (JPA adapter, repository implementation):


// Layer 1: Domain Port (interface)
public interface UserRepository {
    Optional<User> findByEmail(Email email);
    User save(User user);
}

// Layer 3: Infrastructure Adapter (implementation with JPA)
@Repository
public class UserJpaAdapter implements UserRepository {
    private final UserJpaRepository jpaRepository;
    private final UserJpaMapper mapper;

    @Override
    public Optional<User> findByEmail(Email email) {
        return jpaRepository.findByEmailValue(email.value())
            .map(mapper::toDomain);
    }

    @Override
    public User save(User user) {
        UserJpaEntity entity = mapper.toJpa(user);
        UserJpaEntity saved = jpaRepository.save(entity);
        return mapper.toDomain(saved);
    }
}

// Integration Test: validates that adapter persists and retrieves correctly
@DataJpaTest
@Import({UserJpaAdapter.class, UserJpaMapper.class})
class UserJpaAdapterIntegrationTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @Autowired
    private UserJpaAdapter adapter;

    @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);
    }

    @Test
    void testAdapterImplementsPortCorrectly() {
        Email email = new Email("test@example.com");
        User user = User.register(email, BCrypt.hashpw("pwd", BCrypt.gensalt()));

        // Save via adapter (uses JPA)
        User saved = adapter.save(user);

        // Retrieve via adapter
        Optional<User> retrieved = adapter.findByEmail(email);

        assertTrue(retrieved.isPresent());
        assertEquals(saved.id(), retrieved.get().id());
        // Domain logic is NOT affected by persistence details
    }
}
  

PostgreSQL + Redis + Docker Compose

For tests that require both PostgreSQL and Redis:


@SpringBootTest
class PostgresRedisIntegrationTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
    static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine")
        .withExposedPorts(6379);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

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

    @Test
    void testUserPersistenceAndCaching() {
        User user = User.register(new Email("cache@example.com"), "hash");
        userRepository.save(user);

        // Uses Redis for caching
        redisTemplate.opsForValue().set("user:cache@example.com", "cached_user_data");
        String cached = redisTemplate.opsForValue().get("user:cache@example.com");

        assertEquals("cached_user_data", cached);
    }
}
  

CI/CD: Testcontainers in GitHub Actions

On CI/CD (GitHub Actions), Docker is already available, Testcontainers works perfectly:


name: Integration Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'

      - name: Run Integration Tests
        run: mvn test -DskipTests=false -Dgroups="integration"

      - name: Upload Coverage
        uses: codecov/codecov-action@v3
        with:
          files: ./target/site/jacoco/index.html
  

Testcontainers starts the containers automatically. No special Docker service configuration required.

Anti-Pattern 1: Container per Single Test

WRONG:


// DON'T do this! Creates a new container PER EACH @Test
@SpringBootTest
class SlowTestExample {

    // Non-static container: one new per test
    PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    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);
    }

    @Test
    void testUser1() { /* ... */ }  // Starts container, ~5s

    @Test
    void testUser2() { /* ... */ }  // Starts NEW container, ~5s

    @Test
    void testUser3() { /* ... */ }  // Starts NEW container, ~5s
    // Total time: ~15s + overhead, when it could be ~5s with static container
}
  

CORRECT:


// Use static container: started once, shared across tests
@SpringBootTest
class FastTestExample {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @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);
    }

    @Test
    void testUser1() { /* ... */ }  // Container already started

    @Test
    void testUser2() { /* ... */ }  // Reuses container

    @Test
    void testUser3() { /* ... */ }  // Reuses container
    // Total time: ~5s, not 15s
}
  

Anti-Pattern 2: Hard-coded Database URL

WRONG:


@SpringBootTest
class HardcodedDbTest {

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        // Hard-coded URL: the container will have a different port each time!
        registry.add("spring.datasource.url",
            () -> "jdbc:postgresql://localhost:5432/testdb");  // WRONG
    }
}
  

CORRECT:


@SpringBootTest
class ProperDbTest {

    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        // Reads dynamically from container: correct port always
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
    }
}
  

FAQ - 5 Common Questions

Q1. Does Testcontainers require Docker installed?

Answer: Yes. Docker Desktop (macOS/Windows) or Docker Engine (Linux) is required. The Docker daemon must be active during testing. On CI/CD (GitHub Actions), Docker is pre-installed.

Q2. Can I combine Testcontainers with @MockBean?

Answer: Yes. Use @SpringBootTest with Testcontainers for the real database, and @MockBean for external services (EmailSender, PaymentGateway). Example:


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

    @MockBean
    private EmailSender emailSender;

    @Autowired
    private RegisterUserUseCase registerUseCase;

    @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);
    }

    @Test
    void testRegisterAndMockEmail() {
        registerUseCase.execute(new RegisterUserRequest("user@example.com", "pwd"));
        verify(emailSender).sendWelcome(any());
    }
}
  

Q3. Is Testcontainers slow for local development?

Answer: No. The PostgreSQL container starts in ~2-3 seconds. With container reuse (static container), 10-15 tests run in ~5-8 seconds total. For fast local dev, the pyramid's lower tests (pure domain unit tests) remain sub-100ms.

Q4. Can I test Flyway migrations with Testcontainers?

Answer: Yes. Enable Flyway in @DynamicPropertySource and migrations execute automatically:


@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.flyway.enabled", () -> "true");
    registry.add("spring.flyway.locations", () -> "classpath:db/migration");
}
  

Q5. Does Testcontainers support MySQL, Oracle, other databases?

Answer: Yes. Testcontainers supports MySQLContainer, OracleContainer, MongoDBContainer, ElasticsearchContainer, and many others. Use the corresponding Maven module.

Conclusion: Testcontainers for Real Testing

The 4 patterns of Testcontainers (shared @SpringBootTest, @DataJpaTest, @Nested organization, PostgreSQL+Redis) transform integration tests from mock-based to database-real. In Federico's portfolio backend, every adapter and repository layer has Testcontainers PostgreSQL tests, eliminating the gap between "test passed" and "production failed".

Testcontainers is the industry standard for integration testing in modern Java. Use it.

External Resources and Further Reading

Subscribe to the Newsletter

Get enterprise Java patterns, Spring Boot testing best practices and architecture delivered to your inbox. Every Wednesday: 1 pattern, 1 gotcha, 1 resource. Subscribe (Substack link).

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects