Setup Test Database
In our previous lesson, we configured PostgreSQL as our production database.
Setting up a separate test database will allow us to run tests without requiring PostgreSQL to be running.
This separation of test and production databases is crucial for reliable continuous integration and development workflows.
Understanding Test Database Requirements
Spring Boot provides excellent support for using different databases in different environments.
The H2 database is an excellent choice for testing because it runs in memory and doesn't require external setup.
This approach ensures our tests are fast, reliable, and truly isolated from the production environment.
Observing the Current Problem
If we try running tests with PostgreSQL stopped, we'll see failures:
docker-compose down
./mvnw testThe test failure occurs because our application tries to connect to PostgreSQL, which isn't available:
Connection to localhost:5432 refused
Configuring the Test Database
Create a new file src/test/resources/application.properties with the following configuration:
# Test Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
# JPA Configuration
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=trueUnderstanding the Configuration
The jdbc:h2:mem:testdb URL specifies an in-memory database that's created fresh for each test run.
The create-drop setting ensures our database schema is created before tests and dropped afterward, providing a clean slate for each test.
Spring Boot automatically prioritizes test-specific properties files during test execution.
Verifying the Setup
Now we can run our tests without PostgreSQL running:
./mvnw testThe tests should now pass, using the H2 database instead of PostgreSQL.
Summary
- H2 provides a lightweight, in-memory database perfect for testing
- Separate application.properties files enable environment-specific configurations
- The create-drop setting ensures a clean test database for each test run
- Spring Boot automatically selects the appropriate database configuration based on the runtime environment
- Independent test databases enable reliable continuous integration pipelines