Fix Tests

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 test

The 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=true

Understanding 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 test

The 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

  • Independent test databases enable reliable continuous integration pipelines

© 2026 Devtiro Ltd. All rights reserved