0
0
Spring Bootframework~5 mins

Test containers for database testing in Spring Boot

Choose your learning style9 modes available
Introduction

Test containers help you run real databases in temporary containers during tests. This makes tests more reliable and close to real use.

You want to test your Spring Boot app with a real database without installing it locally.
You need to ensure your database queries work correctly in integration tests.
You want isolated database environments for each test run to avoid conflicts.
You want to automate database testing in your CI/CD pipeline.
You want to avoid using in-memory databases that behave differently from your real database.
Syntax
Spring Boot
import org.testcontainers.containers.PostgreSQLContainer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;

public class MyDatabaseTest {
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
        .withDatabaseName("testdb")
        .withUsername("user")
        .withPassword("pass");

    @BeforeAll
    public static void startContainer() {
        postgres.start();
    }

    @AfterAll
    public static void stopContainer() {
        postgres.stop();
    }

    // Use postgres.getJdbcUrl(), getUsername(), getPassword() in your tests
}

Use the container's JDBC URL and credentials to connect your app during tests.

Containers start before tests and stop after to keep tests isolated.

Examples
Creates a PostgreSQL container with a specific database name and user credentials.
Spring Boot
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
    .withDatabaseName("testdb")
    .withUsername("user")
    .withPassword("pass");
Starts the container before all tests run.
Spring Boot
@BeforeAll
public static void startContainer() {
    postgres.start();
}
Stops the container after all tests finish.
Spring Boot
@AfterAll
public static void stopContainer() {
    postgres.stop();
}
Get connection details from the running container to use in your test configuration.
Spring Boot
String url = postgres.getJdbcUrl();
String user = postgres.getUsername();
String pass = postgres.getPassword();
Sample Program

This test starts a PostgreSQL container, creates a table, inserts a message, and checks it. It prints the message to show the test ran.

Spring Boot
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class DatabaseTest {
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
        .withDatabaseName("testdb")
        .withUsername("user")
        .withPassword("pass");

    @BeforeAll
    public static void startContainer() {
        postgres.start();
    }

    @AfterAll
    public static void stopContainer() {
        postgres.stop();
    }

    @Test
    public void testSimpleQuery() throws Exception {
        String url = postgres.getJdbcUrl();
        String username = postgres.getUsername();
        String password = postgres.getPassword();

        try (Connection conn = DriverManager.getConnection(url, username, password);
             Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE greetings (message VARCHAR(255));");
            stmt.execute("INSERT INTO greetings VALUES ('Hello, Testcontainers!');");

            ResultSet rs = stmt.executeQuery("SELECT message FROM greetings;");
            if (rs.next()) {
                String message = rs.getString("message");
                assertEquals("Hello, Testcontainers!", message);
                System.out.println(message);
            }
        }
    }
}
OutputSuccess
Important Notes

Testcontainers require Docker installed and running on your machine.

Use the exact container image version to avoid unexpected changes.

Always stop containers after tests to free resources.

Summary

Testcontainers let you run real databases in temporary containers for testing.

They help make integration tests reliable and close to real use.

Start containers before tests and stop them after to keep tests clean and isolated.