Replace H2 with a real database for testing
Table of contents
Replace your H2 in-memory test database with a real PostgreSQL instance
using the Testcontainers special JDBC URL — a one-line change.
Time to complete
15 minutes
In this guide, you will learn how to:
- Understand the drawbacks of using H2 in-memory databases for testing
- Replace H2 with a real PostgreSQL database using the Testcontainers special JDBC URL
- Use the Testcontainers JUnit 5 extension for more control over the container
- Test both Spring Data JPA and JdbcTemplate-based repositories
Prerequisites
- Java 17+
- Maven or Gradle
- A Docker environment supported by Testcontainers
NoteIf you're new to Testcontainers, visit the Testcontainers overview to learn more about Testcontainers and the benefits of using it.
Modules
- The H2 problem
Understand why using H2 in-memory databases for testing gives false confidence.
- JDBC URL approach
Use the Testcontainers special JDBC URL to swap H2 for a real PostgreSQL database.
- JUnit 5 extension
Use the Testcontainers JUnit 5 extension for more control over the PostgreSQL container.