Spring Boot Testcontainers For Database Testing

Writing database tests that mimic real-world scenarios is crucial β€” but in-memory databases like H2 often fall short in simulating true production environments. This is where Testcontainers comes in. Testcontainers is a Java library that provides lightweight, throwaway instances of common databases (like PostgreSQL, MySQL) inside Docker containers for your tests.

In this post, we’ll explore Spring Boot Testcontainers Database Testing, showing you how to run real PostgreSQL containers for integration tests that are fast, repeatable, and production-representative.

Spring Boot Testcontainers For Database Testing

πŸ“¦ Project Setup

πŸ”§ Prerequisites:

  • Java 17+ (recommended)
  • Docker installed and running
  • Spring Boot 3.x

🧾 Maven Dependencies:

πŸ— Project Structure

🧱 Entity: Customer

πŸ“‚ Repository Interface

πŸ§ͺ Integration Test with Testcontainers

Here’s how to create a reusable PostgreSQL container for all your Spring Boot integration tests.

βš™οΈ How It Works

  • @Testcontainers: Activates Testcontainers JUnit integration
  • @Container: Lifecycle-managed PostgreSQL container
  • @DynamicPropertySource: Dynamically injects DB properties into Spring’s Environment
  • @DataJpaTest: Loads only the JPA-related components for fast test execution

βœ… Benefits of Spring Boot Testcontainers Database Testing

BenefitDescription
πŸ§ͺ Real EnvironmentUses PostgreSQL/MySQL as in production
πŸš€ Fast & IsolatedContainers are ephemeral and disposable
πŸ” RepeatableSame test setup on every run
🌍 CI/CD FriendlyWorks on local or cloud build agents with Docker

🧠 Tips for Best Practices

  • Prefer one container per test class to improve performance.
  • Use @TestConfiguration if you need to add beans during testing.
  • Use @SpringBootTest instead of @DataJpaTest if testing with services/controllers.
  • Clean up DB state between tests using @BeforeEach or @DirtiesContext.

πŸ“š Summary

In this guide, you learned how to implement Spring Boot Testcontainers Database Testing using PostgreSQL. We covered:

  • Setting up Dockerized PostgreSQL for tests
  • Writing dynamic Spring Boot configurations
  • Running @DataJpaTest with Testcontainers
  • Best practices for production-similar test environments

This approach gives you confidence that your application will behave correctly when deployed to real databases.