0
0
JUnittesting~10 mins

Test containers for database testing in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses Testcontainers to start a temporary PostgreSQL database. It verifies that the application can connect and query the database correctly.

Test Code - JUnit 5
JUnit
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 PostgresContainerTest {

    @Test
    public void testDatabaseConnection() throws Exception {
        try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15.3")) {
            postgres.start();

            String jdbcUrl = postgres.getJdbcUrl();
            String username = postgres.getUsername();
            String password = postgres.getPassword();

            try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
                 Statement stmt = conn.createStatement()) {

                stmt.execute("CREATE TABLE test_table(id INT PRIMARY KEY, name VARCHAR(255));");
                stmt.execute("INSERT INTO test_table VALUES (1, 'Test User');");

                ResultSet rs = stmt.executeQuery("SELECT name FROM test_table WHERE id = 1;");

                if (rs.next()) {
                    String name = rs.getString("name");
                    assertEquals("Test User", name);
                } else {
                    throw new AssertionError("No data found in test_table");
                }
            }
        }
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test method-PASS
2PostgreSQLContainer is created and startedA Docker container with PostgreSQL 15.3 is running and ready to accept connectionsContainer started successfullyPASS
3Connect to the PostgreSQL database using JDBC URL, username, and password from containerConnection to the temporary database is establishedConnection is not null and validPASS
4Execute SQL to create table 'test_table'Table 'test_table' created in the databaseTable creation executed without errorPASS
5Insert a row into 'test_table' with id=1 and name='Test User'One row inserted into 'test_table'Insert executed without errorPASS
6Query 'test_table' for name where id=1ResultSet contains one row with name='Test User'ResultSet has next rowPASS
7Assert that the retrieved name equals 'Test User'Assertion compares expected and actual valuesassertEquals("Test User", name)PASS
8Stop the PostgreSQL container and end the testDocker container is stopped and removed-PASS
Failure Scenario
Failing Condition: The test fails if the container does not start or the database connection cannot be established.
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify after inserting data into the database?
AThat the table 'test_table' exists
BThat the database container is running
CThat the inserted name matches 'Test User'
DThat the connection URL is correct
Key Result
Using Testcontainers allows tests to run against a real database in a clean environment, improving reliability and avoiding dependencies on external databases.