Test Overview
This test uses Testcontainers to start a temporary PostgreSQL database. It verifies that the application can connect and query the database correctly.
This test uses Testcontainers to start a temporary PostgreSQL database. It verifies that the application can connect and query the database correctly.
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"); } } } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes the test method | - | PASS |
| 2 | PostgreSQLContainer is created and started | A Docker container with PostgreSQL 15.3 is running and ready to accept connections | Container started successfully | PASS |
| 3 | Connect to the PostgreSQL database using JDBC URL, username, and password from container | Connection to the temporary database is established | Connection is not null and valid | PASS |
| 4 | Execute SQL to create table 'test_table' | Table 'test_table' created in the database | Table creation executed without error | PASS |
| 5 | Insert a row into 'test_table' with id=1 and name='Test User' | One row inserted into 'test_table' | Insert executed without error | PASS |
| 6 | Query 'test_table' for name where id=1 | ResultSet contains one row with name='Test User' | ResultSet has next row | PASS |
| 7 | Assert that the retrieved name equals 'Test User' | Assertion compares expected and actual values | assertEquals("Test User", name) | PASS |
| 8 | Stop the PostgreSQL container and end the test | Docker container is stopped and removed | - | PASS |