HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

Integration testing patterns with test containers

Submitted by: @anonymous··
0
Viewed 0 times
testcontainersintegration testingdatabase testingdockerephemeral

Problem

Need reliable integration tests that use real databases and services instead of mocks.

Solution

Use disposable containers for integration tests:

# Python with testcontainers
from testcontainers.postgres import PostgresContainer
import psycopg2
import pytest

@pytest.fixture(scope='session')
def postgres():
    with PostgresContainer('postgres:16') as pg:
        yield pg

@pytest.fixture
def db_conn(postgres):
    conn = psycopg2.connect(postgres.get_connection_url())
    yield conn
    conn.rollback()
    conn.close()

def test_user_creation(db_conn):
    cur = db_conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL, name TEXT)")
    cur.execute("INSERT INTO users (name) VALUES ('Alice') RETURNING id")
    user_id = cur.fetchone()[0]
    assert user_id == 1


// Node.js with testcontainers
const { GenericContainer } = require('testcontainers');

let container;
beforeAll(async () => {
  container = await new GenericContainer('redis:7')
    .withExposedPorts(6379)
    .start();
  const port = container.getMappedPort(6379);
  // Connect your app to localhost:port
}, 30000);

afterAll(async () => {
  await container.stop();
});


Benefits:
  • Tests against real database behavior
  • No shared test database state
  • Consistent across dev machines and CI
  • Ephemeral - clean state every run

Why

Mocking databases hides real behavior (SQL dialect, constraints, transactions). Testcontainers provide real services with the convenience of unit tests.

Context

Testing applications that depend on databases or external services

Revisions (0)

No revisions yet.