Testcontainers for Integration Tests: Java and Node.js
Testcontainers spins up real Docker containers (databases, queues, caches) inside your test suite. No mocks, no shared test databases, no "works on my machine" surprises. Java uses the testcontainers library with JUnit 5; Node.js uses testcontainers-node. Both support container reuse to keep test runs fast.
Integration tests that mock the database are not integration tests. They are expensive unit tests that give you false confidence. The moment your ORM generates a query your mock doesn't expect, your tests stay green and production breaks. Testcontainers solves this by running real containers — real PostgreSQL, real Redis, real Kafka — inside your test process, with automatic lifecycle management.
This post covers the full setup for both Java with JUnit 5 and Node.js, including PostgreSQL testing examples and container reuse strategies that keep your CI pipeline from becoming a bottleneck.
What Testcontainers Does
Testcontainers is a library that manages Docker containers programmatically from your test code. Before a test runs, it starts a container. After the test finishes, it tears it down. Everything happens via the Docker daemon on whatever machine runs your tests — your laptop, a CI runner, a GitHub Actions worker.
The key properties:
- Isolation: each test run gets a fresh container, so tests never share state across runs
- Parity: the container image is the same one you use in production — same PostgreSQL version, same Redis configuration
- Portability: works anywhere Docker is available, with no external test infrastructure to maintain
The tradeoff is startup time. A PostgreSQL container takes two to five seconds to start. For a suite of 200 tests this adds up, which is why container reuse matters — covered at the end of this post.
Java Setup with JUnit 5
Add the dependencies to your pom.xml:
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.19.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.19.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.19.7</version>
<scope>test</scope>
</dependency>For Gradle, add to your build.gradle:
testImplementation 'org.testcontainers:testcontainers:1.19.7'
testImplementation 'org.testcontainers:postgresql:1.19.7'
testImplementation 'org.testcontainers:junit-jupiter:1.19.7'Testing with a PostgreSQL Container in Java
The simplest approach uses the @Testcontainers and @Container annotations provided by the JUnit 5 extension:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb")
.withUsername("testuser")
.withPassword("testpass");
private Connection connection;
@BeforeEach
void setUp() throws Exception {
connection = DriverManager.getConnection(
postgres.getJdbcUrl(),
postgres.getUsername(),
postgres.getPassword()
);
// Create schema
try (Statement stmt = connection.createStatement()) {
stmt.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
)
""");
}
}
@Test
void insertsUserAndRetrievesById() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("INSERT INTO users (email) VALUES ('alice@example.com')");
}
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT email FROM users WHERE email = 'alice@example.com'")) {
assertThat(rs.next()).isTrue();
assertThat(rs.getString("email")).isEqualTo("alice@example.com");
}
}
@Test
void rejectsduplicateEmail() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("INSERT INTO users (email) VALUES ('bob@example.com')");
}
assertThatThrownBy(() -> {
try (Statement stmt = connection.createStatement()) {
stmt.execute("INSERT INTO users (email) VALUES ('bob@example.com')");
}
}).hasMessageContaining("duplicate key");
}
}Note the static on the container field. A static container starts once for the entire test class, not once per test method. This alone can cut your test time in half compared to creating a new container per test.
Using with Spring Boot
If you are using Spring Boot, you can wire the container's JDBC URL into your application context using dynamic property registration:
@Testcontainers
@SpringBootTest
class UserServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserService userService;
@Test
void createsUserAndPersistsToDatabase() {
User user = userService.create("charlie@example.com");
assertThat(user.getId()).isNotNull();
assertThat(userService.findById(user.getId())).isPresent();
}
}Spring Boot 3.1 and later has first-class support for Testcontainers through @ServiceConnection, which handles property injection automatically:
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");No @DynamicPropertySource needed — Spring detects the container type and wires the correct properties.
Node.js Setup with testcontainers-node
Install the package:
npm install --save-dev testcontainersYou also need a PostgreSQL client. This example uses pg:
npm install --save-dev pgTesting PostgreSQL in Node.js
Here is a complete Jest test using a PostgreSQL container:
const { PostgreSqlContainer } = require('testcontainers');
const { Client } = require('pg');
describe('UserRepository', () => {
let container;
let client;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16-alpine')
.withDatabase('testdb')
.withUsername('testuser')
.withPassword('testpass')
.start();
client = new Client({
host: container.getHost(),
port: container.getPort(),
database: container.getDatabase(),
user: container.getUsername(),
password: container.getPassword(),
});
await client.connect();
await client.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
)
`);
}, 30000); // Allow 30s for container start on first pull
afterAll(async () => {
await client.end();
await container.stop();
});
afterEach(async () => {
await client.query('TRUNCATE users RESTART IDENTITY CASCADE');
});
test('inserts and retrieves a user by email', async () => {
await client.query('INSERT INTO users (email) VALUES ($1)', ['alice@example.com']);
const result = await client.query(
'SELECT email FROM users WHERE email = $1',
['alice@example.com']
);
expect(result.rows).toHaveLength(1);
expect(result.rows[0].email).toBe('alice@example.com');
});
test('rejects duplicate emails', async () => {
await client.query('INSERT INTO users (email) VALUES ($1)', ['bob@example.com']);
await expect(
client.query('INSERT INTO users (email) VALUES ($1)', ['bob@example.com'])
).rejects.toThrow(/duplicate key/);
});
});The afterEach truncation is important. It resets the table between tests without restarting the container, giving you isolation without the startup cost.
Reusing Containers for Speed
Starting a fresh PostgreSQL container for every test class adds seconds per class. If you have 50 test classes, that is potentially four minutes of container startup time. Testcontainers supports container reuse to eliminate this.
Java: Singleton Container Pattern
Create a base class that all test classes extend:
public abstract class PostgresIntegrationTest {
static final PostgreSQLContainer<?> POSTGRES;
static {
POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine")
.withReuse(true);
POSTGRES.start();
}
}The .withReuse(true) flag tells Testcontainers to check if a container with the same configuration is already running and reuse it instead of starting a new one. The reuse key is computed from the container image and configuration, so different configurations still get separate containers.
You also need to enable reuse globally by creating ~/.testcontainers.properties:
testcontainers.reuse.enable=trueOr set the environment variable:
TESTCONTAINERS_RYUK_DISABLED=trueNode.js: Module-Level Singleton
// test-helpers/postgres.js
const { PostgreSqlContainer } = require('testcontainers');
let container;
let connectionConfig;
async function getPostgresContainer() {
if (!container) {
container = await new PostgreSqlContainer('postgres:16-alpine')
.withReuse(true)
.start();
connectionConfig = {
host: container.getHost(),
port: container.getPort(),
database: container.getDatabase(),
user: container.getUsername(),
password: container.getPassword(),
};
}
return connectionConfig;
}
module.exports = { getPostgresContainer };Use it across your test files:
const { getPostgresContainer } = require('../test-helpers/postgres');
const { Client } = require('pg');
describe('OrderRepository', () => {
let client;
beforeAll(async () => {
const config = await getPostgresContainer();
client = new Client(config);
await client.connect();
});
});Measuring the Impact
Without reuse, a suite with 10 test classes might take:
- Container startup: 3s × 10 = 30s
- Actual tests: 15s
- Total: 45s
With reuse:
- Container startup: 3s × 1 = 3s
- Actual tests: 15s
- Total: 18s
That is a 60% reduction for a modest suite. For larger suites with dozens of test classes, the gains compound.
CI Configuration
In GitHub Actions, Docker is available on all ubuntu-latest runners. No additional setup is needed:
name: Integration Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
- name: Run integration tests
run: ./mvnw test
env:
TESTCONTAINERS_REUSE_ENABLE: trueFor Node.js:
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm test
env:
TESTCONTAINERS_RYUK_DISABLED: trueCommon Pitfalls
Image not found on first run. The first time Testcontainers pulls an image it can take 30–60 seconds depending on network speed. Set your test timeout accordingly — beforeAll timeouts in Jest default to 5 seconds, which is too short for an image pull. Set jest.setTimeout(60000) or pass the timeout as the second argument to beforeAll.
Port conflicts. Testcontainers always maps to a random available port on the host, so port conflicts are not a concern. Never hardcode port numbers — always call container.getPort() or the equivalent.
Container not stopping on test failure. Testcontainers uses a Ryuk sidecar container to clean up containers even if your test process crashes. This is why the TESTCONTAINERS_RYUK_DISABLED flag exists — setting it in reuse scenarios prevents Ryuk from killing your shared container between test classes.
Wrapping Up
Testcontainers gives you integration tests that actually test integration. The cost is a few seconds of startup time; the benefit is confidence that your queries, migrations, and data access patterns work against a real database engine. Combined with container reuse, the startup overhead becomes negligible even for large test suites. Start with a single test class using a PostgreSQL container, verify it works in CI, then expand to other services as needed.