Testcontainers isolation
What you will learn
Testcontainers starts disposable dependencies for integration tests. It is a test orchestration library, not a security boundary for arbitrary code. Use it only on an approved isolated worker and validate actual database state, reset, and cleanup. A missing daemon is an unexecuted test, not a pass.
- Explain container ownership and test lifecycle.
- Separate migration and rollback testing from framework configuration.
- Design bounded fixture resets and failure cleanup.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Framework examples require the companion Maven project or are reviewed artifacts. Their predicted results are not execution evidence.
Reset a test-owned fixture
public class Main {
public static void main(String[] args) throws Exception {var root=java.nio.file.Files.createTempDirectory("bm-v46-"); try { var data=root.resolve("fixture.txt"); java.nio.file.Files.writeString(data,"4"); System.out.println(java.nio.file.Files.readString(data)); java.nio.file.Files.delete(data); System.out.println(java.nio.file.Files.exists(data)); } finally {java.nio.file.Files.deleteIfExists(root.resolve("fixture.txt"));java.nio.file.Files.delete(root);} }}Expected output:
4falseThe fixture owns its directory and removes only its own files; a database reset requires its own mechanism.
Container lifecycle and isolation
A static @Container in a JUnit test class is shared across methods of that class; an instance container is restarted per test. Reuse does not reset tables automatically. Read host and mapped port from Testcontainers rather than assuming a fixed local port. Use a reviewed image digest for reproducibility, wait for readiness, cap startup and query time, and close connections. Do not use reusable containers for tests that require fresh state.
Security gates and evidence
A container daemon can have broad host authority. Never expose the host Docker socket to learners, never run untrusted tests in this environment, and use a dedicated controlled worker with resource and network limits. A tag is not immutable; approve a digest before execution. A simple SQL file demonstrates a migration fixture but not Flyway history or upgrade validation. Do not silently skip container tests and report green integration coverage; report not run separately.
Cleanup on failure
public class Main { record Fixture(java.util.concurrent.atomic.AtomicBoolean closed) implements AutoCloseable { void fail(){throw new IllegalStateException("failed");} public void close(){closed.set(true);} } public static void main(String[] args) {var released=new java.util.concurrent.atomic.AtomicBoolean(); try(var resource=new Fixture(released)) {resource.fail();} catch(IllegalStateException e) {System.out.println(e.getMessage());} System.out.println(released.get()); }}Expected output:
failedtrueCleanup occurs when the body throws; a real worker must also handle abrupt process termination.
Review a migration fixture
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/resources/db/V1__catalog.sql; use the companion lab README.
CREATE TABLE inventory (tenant varchar(30) NOT NULL, sku varchar(30) NOT NULL, quantity integer NOT NULL CHECK (quantity >= 0), PRIMARY KEY (tenant,sku));Predicted behavior: Creates tenant-scoped primary key and quantity constraint.
The SQL is intended for a fresh PostgreSQL database; no migration engine is executed.
PostgreSQL container rollback test
Source-reviewed, NOT RUN. File lab-fixtures/enterprise-testing-v46/src/test/java/lab/CatalogContainerTest.java; use the companion lab README.
package lab;import java.sql.*;import java.time.Duration;import java.nio.charset.StandardCharsets;import org.junit.jupiter.api.Test;import org.testcontainers.junit.jupiter.Container;import org.testcontainers.junit.jupiter.Testcontainers;import org.testcontainers.postgresql.PostgreSQLContainer;import static org.junit.jupiter.api.Assertions.*;@Testcontainersclass CatalogContainerTest { @Container static final PostgreSQLContainer db = new PostgreSQLContainer(approvedImage()) .withDatabaseName("lab").withUsername("lab").withPassword("lab-only") .withStartupTimeout(Duration.ofSeconds(90)); static String approvedImage() { String image = System.getenv("LAB_POSTGRES_IMAGE"); if (image == null || !image.matches("postgres:17[.]6@sha256:[0-9a-f]{64}")) throw new IllegalStateException("Supply an approved PostgreSQL image digest"); return image; } @Test void migrationAndRollback() throws Exception { try (var input = getClass().getResourceAsStream("/db/V1__catalog.sql")) { assertNotNull(input); String sql = new String(input.readAllBytes(), StandardCharsets.UTF_8); try (var c = DriverManager.getConnection(db.getJdbcUrl()+"?connectTimeout=5&socketTimeout=5", db.getUsername(), db.getPassword()); var s = c.createStatement()) { s.setQueryTimeout(5); s.execute(sql); c.setAutoCommit(false); s.executeUpdate("INSERT INTO inventory VALUES ('alpha','pen',4)"); c.rollback(); try (var rows = s.executeQuery("SELECT count(*) FROM inventory")) { assertTrue(rows.next()); assertEquals(0, rows.getInt(1)); } c.rollback(); } } }}Predicted behavior: Migration succeeds and rolled-back insert leaves zero rows.
Run only on an approved dedicated daemon, with an immutable approved image and explicit process deadline.
Common mistakes
Do not confuse a shared container with a fresh database, or connect tests to production through inherited environment configuration. Do not count a container startup as a passing business assertion.
Practice
Write a small AutoCloseable fixture that sets a cleanup flag and check the flag after both successful use and a deliberately thrown exception.
Expected output:
truetrueCompare with the manual review criteria.
Official reading: Testcontainers · Container lifecycle · Boot BOM. External test execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testcontainers isolation — knowledge check
Enterprise testing reasoning.
What is a static @Container lifecycle?
Where may learner tests access Docker?
What does an image digest provide?
What if Docker is absent?
Does a container reset database data per method automatically?