Software Testing
Database Testing Best Practices
This course teaches quality assurance professionals and developers how to verify that the data layer of an application behaves correctly, stays consistent, and performs well under real conditions. You will learn to test schema design, referential integrity, stored procedures, triggers, transactions, migrations, and data quality rules, using widely available tools such as SQL, pytest, Testcontainers, and Great Expectations. The course walks through setting up isolated test environments, writing repeatable data-driven tests, validating CRUD operations against business rules, and catching silent data corruption before it reaches production. It also covers how to integrate database checks into a continuous integration pipeline so that schema changes and data migrations are verified automatically on every commit. By the end, learners will be able to design a database testing strategy that complements application-level end-to-end testing and protects the integrity of the system's most valuable asset: its data.
Intermediate · By the Xtest team · About 41 minutes to read
Introduction
Databases sit underneath almost every application, yet they are often the least tested part of a system. A bug in a user interface is visible the moment it happens; a bug in a database, such as a broken foreign key constraint, a silently failing trigger, or a migration that drops a column of real data, can go unnoticed for months while it quietly corrupts records. Database testing is the discipline of verifying that a database's structure, the data stored in it, and the logic that runs inside it (stored procedures, triggers, constraints) all behave the way the business expects, under both normal and edge-case conditions. This course treats database testing as a first-class engineering practice, not an afterthought bolted onto application testing. You will learn the different layers of database testing, from structural checks on schema design to functional checks on CRUD operations, data integrity rules, transaction behavior, and performance under realistic query loads. Each concept is backed by runnable examples using SQL, Python's pytest framework, Testcontainers for spinning up disposable database instances, and Great Expectations for data quality rules. The course favors practices that work with any relational database engine, so the techniques transfer whether your project uses PostgreSQL, MySQL, SQL Server, or another engine. By the end of this course you will be able to build a test suite that protects data integrity as confidently as your application code is already protected by unit and end-to-end tests.
Foundations of Database Testing
Database testing verifies four distinct layers of a system, and conflating them is the most common reason test suites end up incomplete. The first layer is structural testing: does the schema match what was designed, are data types correct, are primary keys, foreign keys, indexes, and constraints present, and did a migration apply cleanly without losing data. The second layer is functional testing: do CRUD operations, stored procedures, triggers, and views produce the results the business logic expects, including on boundary values and invalid input. The third layer is data integrity testing: does the data stay internally consistent, are referential integrity rules enforced, do default values and NOT NULL constraints hold, and does a transaction either fully commit or fully roll back on failure. The fourth layer, covered later in this course, is performance under realistic query volume.
A sound database testing strategy starts with an isolated, disposable test environment. Testing against a shared development database, let alone production, produces flaky results because other processes change the data underneath your tests. The recommended pattern is to spin up a fresh database instance for each test run (or each test), seed it with known data, run the test, and tear the instance down. Tools such as Testcontainers make this practical by launching a real database engine in a container for the duration of a test suite, so tests run against the same engine used in production rather than a lightweight stand-in.
Writing the tests themselves follows the same arrange-act-assert shape as any other automated test: arrange known seed data, act by running a query, stored procedure, or application code path that touches the database, then assert on the resulting rows, constraint violations, or returned values. Each test should clean up after itself, typically by running inside a transaction that is rolled back at the end, so tests never leak state into one another. This section builds the foundation the rest of the course relies on: a repeatable, isolated way to exercise a database and assert on its behavior.
Types of Database Testing
Structural testing confirms the schema itself is correct: every table has the expected columns, every column has the expected data type and nullability, every primary and foreign key exists, and every index that performance depends on is actually present. This is usually checked by querying the database's own metadata (information_schema in most SQL engines) and comparing it against an expected definition, or by running the project's migration tool and confirming it completes without error.
Functional testing exercises the logic that lives inside the database: stored procedures, triggers, views, and computed columns. A stored procedure that calculates a discount, for example, should be tested the same way a function in application code would be, with a range of normal inputs, boundary inputs (zero, negative, maximum), and invalid inputs that should raise an error.
Data integrity testing checks that the rules protecting the data actually hold under pressure: that a foreign key really does block an orphaned row, that a NOT NULL column really does reject a null, that a unique constraint really does reject a duplicate, and that a multi-step business transaction either fully commits or fully rolls back if any step fails partway through. These three types together, structural, functional, and integrity, form the core of a database test suite before performance testing is even considered.
Setting Up an Isolated Test Database Environment
An isolated test environment is the foundation that makes every other test reliable. The simplest approach for a relational database is to run the real database engine in a container, created fresh for the test run and destroyed afterward, so tests never depend on leftover state from a previous run or interfere with a colleague's work. Testcontainers (available for Python, Java, Node.js, and other languages) is built for exactly this: it starts a real PostgreSQL, MySQL, or other engine in Docker, waits until it is ready to accept connections, and hands your test code a connection string.
Once the container is running, the test setup should apply the project's actual migrations, the same ones that will run in production, rather than a hand-written schema that can drift out of sync. Seed data should be minimal and purposeful: just enough rows to exercise the behavior under test, created through the same insert statements or fixtures used across the suite so that tests stay readable.
Each individual test should run inside a database transaction that begins before the test and rolls back after it, regardless of whether the test passed or failed. This keeps every test independent: a test that inserts a row never affects the test that runs after it. For stored procedures or triggers that themselves manage transactions, a fresh container per test file, rather than per individual test, is often a more practical tradeoff between isolation and speed.
-- Verify a foreign key constraint actually rejects an orphaned row
BEGIN;
INSERT INTO orders (id, customer_id, total)
VALUES (1001, 999999, 49.99);
-- customer_id 999999 does not exist in the customers table
ROLLBACK;
-- Expected: the INSERT above raises a foreign key violation error
-- and no row is ever committed to the orders table.
A direct SQL check that a foreign key constraint between orders and customers is enforced, run inside a transaction so the attempted bad insert never actually lands in the database.
import pytest
import psycopg2
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="module")
def db_connection():
with PostgresContainer("postgres:15") as postgres:
conn = psycopg2.connect(postgres.get_connection_url().replace("postgresql+psycopg2", "postgresql"))
# Apply schema the same way production does
with conn.cursor() as cur, open("migrations/001_init.sql") as f:
cur.execute(f.read())
conn.commit()
yield conn
conn.close()
@pytest.fixture
def db_cursor(db_connection):
cur = db_connection.cursor()
yield cur
db_connection.rollback() # undo anything this test did
cur.close()
def test_duplicate_email_is_rejected(db_cursor):
db_cursor.execute(
"INSERT INTO users (email, name) VALUES (%s, %s)",
("alice@example.com", "Alice")
)
with pytest.raises(psycopg2.errors.UniqueViolation):
db_cursor.execute(
"INSERT INTO users (email, name) VALUES (%s, %s)",
("alice@example.com", "Alice Again")
)
A pytest suite that launches a real PostgreSQL instance in a container, applies the project's own migration file, and asserts that a unique constraint on email rejects a duplicate, with each test rolled back afterward for isolation.
# Spin up a disposable Postgres instance for local manual testing
docker run --rm -d \
--name db-test \
-e POSTGRES_PASSWORD=testpass \
-e POSTGRES_DB=app_test \
-p 5433:5432 \
postgres:15
# Wait for it to accept connections, then apply migrations
until docker exec db-test pg_isready -U postgres; do sleep 1; done
psql -h localhost -p 5433 -U postgres -d app_test -f migrations/001_init.sql
# Tear it down when done
docker stop db-test
A shell script that starts a throwaway PostgreSQL container, waits for it to be ready, applies the project's migration file, and stops the container when testing is finished.
Tips
- Always run database tests against the same engine and version used in production; a lighter stand-in database can hide bugs that only appear on the real engine.
- Wrap each test in a transaction that rolls back afterward so tests never leak state into one another, rather than manually deleting rows at the end of each test.
- Seed only the data a specific test needs; large shared fixture datasets make it hard to tell which row a test actually depends on.
- Run the project's real migration scripts to build the test schema instead of a separately maintained schema file, so the two can never drift apart.
Common pitfalls
- Testing against a shared development or staging database: another process can change rows mid-test, producing flaky failures. Fix this by giving every test run its own disposable database instance.
- Forgetting to test constraint violations, only testing the happy path where data is valid. Fix this by writing a test for every constraint (NOT NULL, UNIQUE, foreign key, CHECK) that deliberately tries to violate it and asserts the database rejects it.
- Letting test data accumulate across runs because cleanup was skipped on a failing test. Fix this by rolling back a transaction in a fixture's teardown step unconditionally, so cleanup happens whether the test passed or failed.
- Writing the expected schema by hand in the test suite instead of applying the project's real migrations, which lets the two definitions quietly drift apart. Fix this by always testing against a schema built from the actual migration scripts.
Data Integrity and Constraint Validation
Data integrity testing confirms that a database enforces the rules it was designed to enforce, independent of whatever application code sits on top of it. A constraint that silently fails to block bad data is often worse than no constraint at all, because teams trust it and stop checking for the problem themselves. This section covers systematic testing of NOT NULL, UNIQUE, CHECK and foreign key constraints, validation of cascading deletes and updates, testing of default values, and the use of reusable data quality tooling such as Great Expectations.
The core discipline is to treat constraints as testable contracts. For every constraint defined in a schema, write at least one test that proves the constraint rejects a violating insert or update, and at least one test that proves valid data still passes. Testing only the happy path leaves the actual protective behavior of the constraint unverified: a NOT NULL column that was never tested with an explicit null insert has not actually been tested.
Cascading behavior deserves special attention because it changes the state of rows the test did not directly touch. A deletion on a parent table might cascade, restrict, or set a foreign key to null depending on how the relationship was defined, and these behaviors are easy to get wrong during a schema migration. Tests should insert a known parent and child, perform the deleting or updating operation, and then assert on the exact resulting state of the child rows, not just that the operation did not error.
Default values are another quiet source of bugs. A default that was correct when the schema was first written can become wrong as business rules evolve, and nothing in the application layer will catch it if no row ever triggers a test for it directly.
Testing Constraints Directly Against the Schema
The most reliable way to test a constraint is to attempt to violate it directly with a raw insert or update, rather than only going through application code that might add its own validation layer before the database is ever reached. This isolates the database's own enforcement from the application's, which matters because an application bug can mask a missing database constraint for a long time until a second code path writes to the same table without the same checks.
For each constraint type, structure tests around the boundary: a NOT NULL test inserts a row with the column explicitly omitted or set to null and expects an error; a UNIQUE test inserts a duplicate value and expects an error on the second insert, not the first; a CHECK constraint test tries values on both sides of the boundary, for example a negative value against a CHECK (price >= 0) rule and a value of exactly zero. Foreign key tests should attempt to insert a child row referencing a parent id that does not exist, and separately confirm that inserting a child row with a valid parent id succeeds.
It is worth running these tests against the same database engine and version used in production, since constraint behavior (such as how NULL interacts with a UNIQUE index) can differ subtly between engines. Keep each test isolated in its own transaction that rolls back afterward, so constraint violation tests never leave partial data behind for later tests to trip over.
Validating Cascades, Defaults, and Reusable Data Quality Rules
Cascading deletes and updates should be tested by setting up a small, deliberate object graph: one parent row and two or three child rows, with at least one child belonging to a different parent as a control. After the cascading operation runs, assert on all three groups: the deleted or updated parent, the children that should have cascaded, and the control children that should be untouched. This control group catches the common bug of a cascade rule that is too broad and silently affects rows it should not.
Default value tests should insert a row while deliberately omitting the column with a default, then read the row back and assert the stored value matches the expected default exactly, including type and precision for numeric and timestamp defaults.
For data quality rules that need to run repeatedly across a growing dataset rather than a single test fixture, a tool such as Great Expectations lets a team define an expectation once, for example that a column's values fall within a range or that a column has no nulls, and then run that same expectation as part of a pipeline, a scheduled job, or a CI check. This turns constraint-style rules that the schema itself cannot express, such as cross-table consistency checks, into a reusable, versioned suite rather than a one-off script.
import pytest
import psycopg2
@pytest.fixture
def conn():
connection = psycopg2.connect("dbname=test_db user=test")
yield connection
connection.rollback()
connection.close()
def test_not_null_constraint_rejects_missing_email(conn):
cur = conn.cursor()
with pytest.raises(psycopg2.errors.NotNullViolation):
cur.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (1, None))
def test_unique_constraint_rejects_duplicate_email(conn):
cur = conn.cursor()
cur.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (1, 'a@example.com'))
with pytest.raises(psycopg2.errors.UniqueViolation):
cur.execute("INSERT INTO users (id, email) VALUES (%s, %s)", (2, 'a@example.com'))
def test_cascade_delete_removes_child_rows_only_for_deleted_parent(conn):
cur = conn.cursor()
cur.execute("INSERT INTO orders (id, user_id) VALUES (10, 1), (11, 2)")
cur.execute("DELETE FROM users WHERE id = 1")
cur.execute("SELECT id FROM orders WHERE user_id = 1")
assert cur.fetchall() == []
cur.execute("SELECT id FROM orders WHERE user_id = 2")
assert cur.fetchall() == [(11,)]
A pytest suite against a real PostgreSQL connection that tests a NOT NULL violation, a UNIQUE violation, and that a cascading delete removes only the child rows of the deleted parent, leaving an unrelated parent's children untouched.
Tips
- Write one test for the constraint failing and one for valid data passing; a constraint that is never tested against a violation has not really been verified.
- Use a control row (a parent or child that should not be affected) in every cascade test so an overly broad cascade rule gets caught instead of passing silently.
- Run constraint tests against the exact database engine and version used in production, since null handling and constraint edge cases can differ between engines.
Common pitfalls
- Testing constraints only through application code, which can hide a missing or misconfigured database-level constraint behind application-level validation that happens to catch the same bad input.
- Asserting only that a cascading operation 'did not error' instead of checking the exact resulting state of every affected and unaffected row, which lets an incorrect cascade scope go unnoticed.
Testing Transactions, Stored Procedures, and Triggers
Transactions, stored procedures, and triggers are where a lot of business logic quietly lives inside the database itself, which makes them easy to under-test. Unlike application code, you cannot always step through them with a debugger, and their effects (a row inserted, a balance updated, a cascading delete) only show up as state changes in the database. This section covers three overlapping concerns: verifying that transactions honor ACID properties under concurrent load, confirming that a multi-step transaction rolls back completely when any step fails partway through, and treating stored procedures, functions, and triggers as first-class units of code that deserve their own test suites.
The core discipline is the same one you'd apply to any code: set up a known starting state, exercise the logic, and assert on the resulting state, then clean up. The difference is that your 'unit' is a SQL object running inside a transactional engine, so your test harness usually wraps each test in its own transaction and rolls it back afterward, or restores a snapshot, so tests never pollute each other or leave residue in a shared database. For concurrency testing, you deliberately open two or more connections and interleave operations to surface race conditions, lost updates, and deadlocks that a single-threaded test would never reveal.
Stored procedures and triggers also need negative testing: what happens when a procedure receives invalid input, when a trigger fires on a bulk update instead of a single row, or when a trigger that should only fire on INSERT is accidentally triggered by an UPDATE. Testing the condition under which something does not happen is just as important as testing that it does.
Verifying Transactional Integrity and Rollback
A transaction test should prove two things: that a successful sequence of statements commits as a single atomic unit, and that a failure at any point rolls back every prior statement in that sequence, leaving no partial writes. Pick a multi-step business operation, such as a funds transfer that debits one account and credits another, and write a test that forces the second step to fail (a constraint violation, a deliberate exception, a disconnected connection) and then asserts that the first step's write never persisted. Run the assertion from a fresh connection, not the one that performed the transaction, so you are checking durable state rather than an in-memory view.
Concurrency tests require at least two connections running in parallel. A classic case is two transactions both reading the same row, both computing a new value, and both writing it back: without correct isolation you lose one of the updates. Script the interleaving explicitly, for example by having one transaction pause after its read (using a sleep or a debug hook) while the second completes its full read-modify-write cycle, then let the first resume and commit. Assert on the final value and check your application's isolation level actually prevents the lost update, since many engines default to READ COMMITTED rather than SERIALIZABLE. Also test for deadlocks by having two transactions lock resources in opposite orders, and confirm your application retries sensibly when the database reports one.
Unit Testing Stored Procedures, Functions, and Triggers
Treat each stored procedure or function like any other unit under test: known inputs, a clean starting state, and an assertion on both the return value and any side effects on the data. Many databases support a pgTAP, tSQLt, or utPLSQL-style framework that runs tests inside the database engine itself, wrapping each test in a transaction that is rolled back automatically, so test data never leaks between runs. If your stack prefers testing from the application layer instead, a script in Python with pytest or in JavaScript with Jest, driving the database through a normal client library, works just as well, as long as each test resets its fixture data.
Triggers need special attention because they fire implicitly rather than being called directly. Write tests for the condition that should fire the trigger (inserting a row that should cascade an update to a related table), and equally important, tests for conditions that should not fire it (an update to an unrelated column, a bulk operation the trigger logic didn't anticipate). Check trigger behavior under bulk statements specifically, since a trigger written assuming a single-row context can silently misbehave, or only process the first row, when a statement affects thousands of rows at once. Also verify that a trigger does not fire recursively or duplicate work when it is itself the cause of another write that could re-trigger it.
import psycopg2
import pytest
@pytest.fixture
def conn():
connection = psycopg2.connect("dbname=testdb user=test")
yield connection
connection.rollback()
connection.close()
def test_transfer_rolls_back_on_failure(conn):
cur = conn.cursor()
cur.execute("INSERT INTO accounts (id, balance) VALUES (1, 100), (2, 50)")
conn.commit()
try:
cur.execute("BEGIN")
cur.execute("UPDATE accounts SET balance = balance - 30 WHERE id = 1")
# Force a failure: account 2 doesn't exist in this scope
cur.execute("UPDATE accounts SET balance = balance + 30 WHERE id = 999")
if cur.rowcount == 0:
raise ValueError("Target account not found")
conn.commit()
except Exception:
conn.rollback()
# Check from a fresh cursor that no partial write persisted
cur.execute("SELECT balance FROM accounts WHERE id = 1")
assert cur.fetchone()[0] == 100
A pytest test that forces a multi-step transfer transaction to fail partway through, then asserts from a clean read that the first update was fully rolled back rather than partially applied.
Tips
- Wrap every test in its own transaction and roll it back at teardown so tests never depend on or pollute each other's data.
- Test concurrency scenarios explicitly with two real connections and controlled interleaving rather than trusting that isolation levels will behave as documented.
- Write at least one negative test per trigger, confirming it stays silent under conditions that resemble but do not match its intended firing condition.
Common pitfalls
- Asserting on state from the same connection that ran the transaction, which can mask rollback bugs because the connection's own view may differ from durable committed state; always verify from a fresh connection.
- Only testing triggers against single-row statements, missing bugs that appear under bulk inserts or updates where the trigger logic assumed exactly one affected row.
Database Performance Testing and Query Analysis
Database performance testing exists to answer one question before it becomes an incident: will this query still be fast once the table has real volume and real concurrency? A query that returns instantly against a hundred seed rows can degrade sharply once it scans millions of rows, especially if an index is missing or a join forces a full table scan. This section covers reading a query execution plan, finding missing indexes, testing against realistic data volume, and setting performance budgets so a regression is caught in CI rather than in production.
Why seed data lies to you
A handful of rows fits entirely in memory and often gets scanned sequentially faster than an index lookup would run, which hides the exact problem you're trying to catch. The only reliable test environment is one sized close to production, whether that means restoring a sanitized production snapshot, or generating synthetic rows at realistic scale with a seeding script.
Reading an execution plan
Every major database can show you how it intends to run a query, and how it actually ran it. In PostgreSQL that's EXPLAIN ANALYZE; in MySQL it's EXPLAIN with ANALYZE since MySQL 8.0.18. The plan tells you whether the engine used an index scan or a sequential scan, how many rows it estimated versus how many it actually touched, and where most of the time went.
Setting a budget
Once you know how a query should perform, write that expectation down as a number: a maximum duration, a maximum number of rows scanned, or a requirement that a specific index gets used. Check that budget in CI on every change to the schema or the query itself, so a missing index or a changed join order fails the build instead of shipping.
Reading and Interpreting Execution Plans
An execution plan is the database's explanation of how it will carry out a query, and EXPLAIN ANALYZE makes it actually run the query and report the real numbers alongside the estimates. The two figures to compare first are the estimated row count and the actual row count at each step: a large gap usually means the table's statistics are stale, which you fix by running ANALYZE (PostgreSQL) or ANALYZE TABLE (MySQL) to refresh them.
Look for a Seq Scan (PostgreSQL) or a 'type: ALL' row (MySQL) on a large table where you expected an index to be used; that's the single most common performance regression in a growing application. A Nested Loop join that looks fine at low volume can become the slowest part of the plan once one side of the join grows, so re-run the same query against production-scale data rather than trusting a plan taken from a small test database.
Most drivers and ORMs can log the plan for you. In a test suite, capture the plan for your critical queries and assert on its shape, not just on the query's wall-clock time, so a change that silently drops an index is caught even if the slower path happens to still finish within budget on a quiet CI box. Re-check plans after every schema migration: adding a column, changing a column's type, or dropping an index that looked unused can each change which path the planner picks.
Testing at Realistic Volume and Setting Budgets
A query that performs well against a few seed rows tells you almost nothing about how it will behave once the table holds the volume you actually expect in production. Build a seeding step that generates data at a realistic order of magnitude, ideally matching the skew of real data too: a users table where one tenant has ten rows and another has ten million will expose join and index problems that evenly distributed synthetic data never will.
Once you can run a query at realistic volume, turn your expectation for it into an explicit, checked budget rather than a note in a document. A budget can be a maximum duration for the query itself, a cap on the number of rows the planner is allowed to scan, or a hard requirement that a particular index is used in the plan. Run that check as part of your normal test suite, on a schedule or on every pull request that touches the schema or the query, so a regression is caught before release rather than after a customer reports a slow page.
Keep the test data and the test environment as close to production shape as you reasonably can: the same database version, the same indexes, and similar statistics. A budget measured on a database with different indexes or a different version is a budget for a different system, and it will pass or fail for reasons that have nothing to do with the change you actually made.
-- Refresh planner statistics first so estimates are accurate
ANALYZE orders;
-- Run the real query and see both the estimate and the actual execution
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at > NOW() - INTERVAL '30 days'
ORDER BY o.created_at DESC
LIMIT 50;
Runs a realistic query with EXPLAIN ANALYZE in PostgreSQL, showing whether the planner used an index on created_at or fell back to a sequential scan, and how many rows were actually touched versus estimated.
import time
import psycopg2
BUDGET_SECONDS = 0.2
def test_recent_orders_query_meets_budget(conn):
cur = conn.cursor()
start = time.perf_counter()
cur.execute(
"SELECT id, total FROM orders WHERE created_at > NOW() - INTERVAL '30 days' ORDER BY created_at DESC LIMIT 50"
)
cur.fetchall()
elapsed = time.perf_counter() - start
assert elapsed < BUDGET_SECONDS, f"Query took {elapsed:.3f}s, budget is {BUDGET_SECONDS}s"
cur.execute(
"EXPLAIN SELECT id, total FROM orders WHERE created_at > NOW() - INTERVAL '30 days' ORDER BY created_at DESC LIMIT 50"
)
plan = "\n".join(row[0] for row in cur.fetchall())
assert "Seq Scan" not in plan, "Query fell back to a sequential scan, an index may be missing"
A plain Python test using psycopg2 that asserts a query finishes within a set time budget against a realistically sized table, and separately checks the plan to make sure it isn't falling back to a sequential scan.
Tips
- Seed test databases with data at a realistic order of magnitude and realistic skew, not just a handful of evenly distributed rows, since small evenly spread datasets hide the exact problems you're testing for.
- Run ANALYZE (or ANALYZE TABLE in MySQL) before capturing a plan, since stale statistics make the planner's row estimates unreliable and can mask a real problem.
- Assert on the shape of the execution plan, not only on wall-clock time, so a missing index is caught even on a fast, quiet CI machine where the query still finishes within budget despite using the wrong path.
Common pitfalls
- Testing only against a small seed dataset: a query that scans a tiny table sequentially can outperform an index lookup, which hides the fact that the same query will be slow at production scale. Fix this by testing against a dataset sized close to production.
- Setting a performance budget once and never re-checking it after schema changes: adding a column, changing a type, or dropping what looked like an unused index can each change which plan the database picks. Re-run your budget checks on every migration, not just once at launch.
Automating Database Tests and Choosing Tools
A database test suite earns its keep only when it runs automatically, alongside the rest of your application tests, every time code changes. This section covers how to structure that suite, which frameworks suit which layer of testing, and how database checks relate to the end-to-end tests that exercise your application through its user interface.
Database testing happens at several levels: unit-style tests of individual queries or stored procedures, integration tests that check an application layer against a real (often containerized) database, and data-quality tests that validate the shape and content of data as it flows through a pipeline. Each level calls for a different tool. General-purpose test runners such as pytest or JUnit are well suited to query-level and integration tests because they let you set up fixtures, run assertions, and tear down state using the same language and CI pipeline as your application code. DbUnit, built for Java projects, specializes in seeding a known dataset before a test and comparing the database's state afterward against an expected dataset, which is useful when a test's whole point is to verify rows changed correctly. Great Expectations takes a different angle: it defines "expectations" about a dataset's shape, such as which columns must never be null or which values must fall in a range, and is better suited to validating data quality in a pipeline than to testing a single transaction.
It is worth being clear about where database testing stops and end-to-end testing begins. End-to-end tools drive an application through its interface and observe what a user would observe; they are not built to inspect your schema or verify rows directly. xtest is one such tool, built for end-to-end testing with AI test agents, and it never connects to your database, so the checks described in this course need their own dedicated tooling and a place of their own in the pipeline, running before or alongside, not instead of, your end-to-end suite.
Organizing a Database Test Suite Alongside Application Tests
Keep database tests in their own directory or module, but run them from the same CI pipeline as your application and end-to-end tests so that a broken query fails the build just as surely as a broken feature. A common layout separates three kinds of test: fast unit tests of pure SQL or stored logic, run against a lightweight or in-memory database; integration tests that exercise your data access layer against a real database engine, usually started in a container for the duration of the test run; and data-quality checks that run on a schedule against production-like data rather than on every commit, since they can be slower and less deterministic.
Name tests after the behavior they verify, not the table they touch, so a failure's name tells you what broke: test_order_total_includes_tax rather than test_orders_table. Each integration test should create its own data, run its assertion, and clean up afterward, rather than relying on data left behind by another test or by a shared fixture that might change. A database reset between test runs, whether through a migration tool, a fixture loader, or a container that is thrown away and recreated, keeps tests independent of one another and of the order they happen to run in.
Finally, decide early where database tests sit relative to your end-to-end suite in the pipeline. Many teams run database and API-level tests first, since they are faster and point more directly at the broken code, and run the full end-to-end suite afterward only if those pass, saving the slower, more expensive run for when the foundation is already known to be sound.
Choosing a Framework for Each Layer
pytest, or an equivalent general-purpose runner in your application's own language, is usually the right default for query-level and integration tests: it needs no special data format, lets you write setup and teardown in the same language as your application, and plugs into the same CI reporting you already use. Reach for DbUnit specifically in a Java codebase where a test's purpose is to compare the database's exact state before and after an operation against a dataset you define in XML or a flat file; it shines at this kind of before-and-after comparison but adds overhead for a simple single-query check.
Great Expectations fits a different job: validating that data flowing through a pipeline, or already sitting in a warehouse, meets rules you define once and then run repeatedly, such as a column never being null, a foreign key always resolving, or a value always falling inside an expected range. It is less suited to testing a single transaction's logic and more suited to catching data drift or quality regressions over time, often run on a schedule rather than on every commit.
Whichever frameworks you choose, keep the boundary between them clear: a transaction-level correctness test belongs with pytest or DbUnit, a dataset-wide quality check belongs with Great Expectations, and neither replaces an end-to-end test that confirms a user-facing flow still works, since none of these tools look at what the user actually sees on screen.
import pytest
import psycopg2
@pytest.fixture
def db_conn():
conn = psycopg2.connect("dbname=test_orders user=test")
yield conn
conn.rollback()
conn.close()
def test_order_total_includes_tax(db_conn):
cur = db_conn.cursor()
cur.execute(
"INSERT INTO orders (subtotal, tax_rate) VALUES (100, 0.08) RETURNING id"
)
order_id = cur.fetchone()[0]
cur.execute("SELECT total FROM orders WHERE id = %s", (order_id,))
total = cur.fetchone()[0]
assert total == pytest.approx(108.00)
A pytest integration test that inserts a row, lets the database compute a derived column, and asserts the result; the fixture rolls back the transaction so the test leaves no data behind.
import great_expectations as gx
context = gx.get_context()
validator = context.sources.pandas_default.read_csv("orders_export.csv")
validator.expect_column_values_to_not_be_null("customer_id")
validator.expect_column_values_to_be_between("total", min_value=0, max_value=100000)
results = validator.validate()
assert results["success"], "Data quality check failed on orders export"
A Great Expectations check run against an exported dataset, verifying that a required column is never null and that a monetary column stays within a sane range.
Tips
- Run database tests against a disposable container or schema rather than a shared development database, so a failed cleanup in one test run never contaminates the next.
- Keep data-quality checks such as Great Expectations expectations in version control next to the schema they validate, so a schema change and its corresponding check move through review together.
- Put fast unit and integration database tests early in the CI pipeline, before the slower end-to-end suite runs, so a broken query is caught in seconds rather than minutes.
Common pitfalls
- Letting tests share one long-lived database without resetting state between runs, which makes a later test's failure depend on an earlier test having run first; fix this by seeding and tearing down data within each test or test file.
- Using a single framework for every layer of database testing, such as trying to express data-quality rules as DbUnit datasets, which makes the rules harder to read and maintain than writing them with a tool built for that purpose.
Integrating Database Tests into CI/CD
Database tests only earn their keep when they run automatically, on every change, before code reaches production. Wiring them into CI/CD turns database testing from an occasional manual exercise into a safety net that catches breaking schema changes, bad migrations, and constraint violations within minutes of a pull request being opened.
The goal is to run the full database test suite against a disposable, production-shaped database for every pull request, not just before a release. This means spinning up a real database instance (via Docker or a testcontainers library), applying every migration in order, loading representative seed or anonymized production-shaped data, running your test suite against it, and tearing it down. Because the environment is ephemeral and created fresh each run, tests stay deterministic and isolated from whatever state a previous run left behind.
A second pillar is testing migrations in both directions. Every migration that can be rolled back should be rolled back in CI, and the schema compared before and after to confirm the rollback is clean. This catches migrations that silently drop data, forget to reverse an index, or leave orphaned constraints behind. Finally, the pipeline must fail loudly and specifically: when a schema change breaks a foreign key, a unique constraint, or a query a test depends on, the build should fail with a clear message naming the broken assertion, not a generic timeout or connection error.
Building this pipeline well means balancing speed and realism: a suite that takes 40 minutes per PR will get skipped or ignored, so parallelizing, caching base images, and trimming seed data to what is actually needed for coverage all matter as much as test correctness itself.
Running the Suite on Every Pull Request
Treat the database test suite as a required status check, exactly like unit tests or linting. On each pull request, the CI job should provision a clean database container (Postgres, MySQL, or whatever your production engine is), run every pending migration against it in order, load a fixture set that mirrors production's shape (including nullable columns, edge-case values, and realistic row counts for any query that depends on volume), and then execute the test suite against that database.
Using a real containerized database instead of an in-memory substitute is important: in-memory databases often don't enforce the same constraint behavior, locking semantics, or query planner decisions as the production engine, so tests that pass against a stand-in can still fail in production. Docker Compose or a testcontainers library (available for most languages) makes spinning up a matching database version in CI straightforward and repeatable.
Keep the suite fast by running independent test files in parallel against separate database instances or separate schemas within one instance, and by caching the base Docker image layers between runs. Separate 'fast' tests (constraint checks, basic CRUD, simple queries) from 'slow' tests (large-volume query performance, full migration replays) into different CI stages so a quick feedback loop is still possible on every push, with the fuller suite running before merge.
Validating Forward and Backward Migrations
A migration is only safe if it works in both directions. In CI, after applying a new migration, the job should also run its rollback (down migration) and verify the schema returns to its prior state: same tables, same columns, same constraints, same indexes. Tools like Flyway and Liquibase support this out of the box by keeping a migration history table and exposing explicit up and down commands, which a CI script can invoke in sequence.
Beyond structural comparison, re-run a subset of the test suite after the rollback to confirm the application code still works against the older schema, catching migrations that quietly depend on a new column existing even though the rollback removed it. This is especially important for migrations that reshape data, such as splitting a column into two or backfilling a new field: the rollback needs a plan for what happens to data written after the forward migration ran, and that plan should be exercised in CI, not discovered during an actual incident.
Finally, validate migrations against a copy of production-shaped data rather than a tiny hand-built fixture. A migration that adds a NOT NULL constraint might pass against three test rows but fail the moment it meets a production table with existing nulls. Anonymized or synthetic data that mirrors production's distribution of nulls, duplicates, and row counts surfaces these problems before they reach a real deployment.
#!/usr/bin/env bash
set -euo pipefail
# Start a disposable Postgres container matching production's version
docker run -d --name db-test -e POSTGRES_PASSWORD=test -p 5432:5432 postgres:15
sleep 3
# Apply all migrations forward
flyway -url=jdbc:postgresql://localhost:5432/postgres -user=postgres -password=test migrate
# Load production-shaped seed data
psql -h localhost -U postgres -f fixtures/seed_prod_shaped.sql
# Run the test suite against the migrated schema
pytest tests/db --maxfail=1
# Roll back the most recent migration and confirm schema matches baseline
flyway -url=jdbc:postgresql://localhost:5432/postgres -user=postgres -password=test undo
pg_dump --schema-only -h localhost -U postgres postgres > after_rollback.sql
diff baseline_schema.sql after_rollback.sql
docker rm -f db-test
A CI script that provisions a Postgres container, applies migrations forward, runs the database test suite against production-shaped seed data, then rolls back the latest migration and diffs the resulting schema against a known-good baseline to catch incomplete rollbacks.
const { GenericContainer } = require('testcontainers');
const { Pool } = require('pg');
describe('order constraint integrity', () => {
let container, pool;
beforeAll(async () => {
container = await new GenericContainer('postgres:15')
.withEnvironment({ POSTGRES_PASSWORD: 'test' })
.withExposedPorts(5432)
.start();
pool = new Pool({
host: container.getHost(),
port: container.getMappedPort(5432),
user: 'postgres',
password: 'test',
});
});
afterAll(async () => {
await pool.end();
await container.stop();
});
test('rejects an order with a negative quantity', async () => {
await expect(
pool.query('INSERT INTO orders (quantity) VALUES (-1)')
).rejects.toThrow(/violates check constraint/);
});
});
A Jest test using testcontainers to start a real Postgres instance for each CI run, verifying that a CHECK constraint on the orders table is still enforced after any schema change, failing the build if a migration accidentally weakens or drops it.
Tips
- Pin the database container to the exact engine version running in production; subtle constraint and locking behavior differs across versions.
- Split the suite into a fast tier (constraints, CRUD) that runs on every push and a slower tier (full migration replay, volume-based queries) that runs before merge, so feedback stays quick.
- Store a known-good schema snapshot in version control and diff against it after every rollback test to catch incomplete down migrations automatically.
Common pitfalls
- Testing against an in-memory or lightweight database substitute instead of the real engine, which hides constraint and query-planner differences that only show up in production.
- Never exercising the rollback (down) migration in CI, so a broken or data-losing rollback is only discovered during an actual incident.
Exercises
Exercise 1: Build an Isolated Test Environment and Validate a Foreign Key
In this exercise you will set up a disposable PostgreSQL instance using Docker, apply a small schema with a parent table (customers) and a child table (orders) linked by a foreign key, and write an automated test that proves the foreign key constraint is actually enforced. This mirrors the real-world situation where a schema migration silently drops a constraint and nobody notices until corrupted data appears in production. You will practice the full loop covered in this section: spinning up a fresh database, applying migrations, seeding minimal data, running an assertion, and tearing everything down cleanly. Pay particular attention to isolation: your test should leave no residue behind, so that running it twice in a row produces the same result both times. This exercise is meant to be done with real tools on your own machine so you build muscle memory for the pattern you will reuse throughout the rest of the course.
- Start a PostgreSQL container locally using Docker, exposing it on a local port.
- Write a migration SQL file that creates a customers table and an orders table with a foreign key from orders.customer_id to customers.id.
- Apply the migration against the running container.
- Write a pytest test that inserts a customer, inserts a matching order, and asserts both inserts succeed.
- Write a second pytest test that attempts to insert an order referencing a non-existent customer_id and asserts that the database raises a foreign key violation.
- Wrap each test in a transaction rollback so the two tests never interfere with each other.
- Run the test suite twice in a row and confirm both runs produce identical results.
Expected outcome: A working pytest suite with two passing tests: one confirming a valid order can be inserted, and one confirming an order referencing a missing customer is rejected by the database's foreign key constraint. Running the suite repeatedly produces the same result every time, with no leftover data between runs.
Exercise 2: Test a Stored Procedure's Transaction Behavior
In this exercise you will write a stored procedure that transfers a balance between two accounts, deducting from one and adding to the other, and then write tests that prove the operation is atomic: if the second step fails for any reason, the first step must also be undone. This is one of the most common sources of real production bugs, where a partial failure leaves the database in an inconsistent state. You will test three scenarios: a successful transfer where both balances update correctly, a failed transfer where the destination account does not exist, and a failed transfer where the source account does not have sufficient funds. For each failure scenario, you must assert not only that an error was raised, but that the source account's balance is completely unchanged afterward, proving the rollback actually happened rather than just assuming it did.
- Create an accounts table with an id and a balance column that cannot go negative (use a CHECK constraint).
- Write a stored procedure or function named transfer_funds that takes a source account id, a destination account id, and an amount, and performs the deduction and addition inside a single transaction.
- Write a test that transfers funds between two existing accounts with sufficient balance and asserts both balances are correct afterward.
- Write a test that attempts to transfer more than the source account's balance and asserts the procedure raises an error.
- In the same test, re-query the source account's balance after the failed attempt and assert it is unchanged from before the attempt.
- Write a test that attempts to transfer to a non-existent destination account id and again confirms the source account's balance is unchanged.
Expected outcome: A stored procedure whose test suite proves atomicity directly: successful transfers update both balances correctly, and every failure scenario leaves the source account's balance exactly as it was before the attempt, with no partial update ever committed.
Quiz
1. Why is it recommended to run database tests against a fresh, disposable database instance rather than a shared development database?
- Disposable instances are always faster to query
- A shared database can be changed by other processes mid-test, producing flaky and unreliable results
- Shared databases do not support foreign keys
- Disposable instances automatically generate test data
Show answer
B. A shared database can be changed by other processes mid-test, producing flaky and unreliable results
A shared database is being used by other people or processes at the same time, so data can change underneath a running test, causing results that are inconsistent from one run to the next. A fresh, isolated instance per test run removes this source of flakiness.
2. What is the purpose of wrapping an individual database test in a transaction that is rolled back afterward?
- To make the test run faster by skipping disk writes
- To automatically fix any bugs found during the test
- To ensure the test's changes never persist, keeping tests independent of one another
- To bypass the database's constraint checks during testing
Show answer
C. To ensure the test's changes never persist, keeping tests independent of one another
Rolling back the transaction after each test undoes every change that test made, so the next test starts from the same known state. This keeps tests independent and prevents one test's leftover data from affecting another.
3. A test suite verifies that inserting a duplicate email into a users table raises a UniqueViolation error. What type of database testing does this represent?
- Performance testing
- Data integrity / constraint testing
- Structural testing of the schema's column types
- Load testing with many simulated users
Show answer
B. Data integrity / constraint testing
Confirming that a UNIQUE constraint actually rejects a duplicate value is a data integrity test: it checks that a rule protecting the data holds up under an attempt to violate it, rather than checking schema structure or performance.
4. Why should a test suite apply the project's actual migration scripts to build the test schema, rather than a separately maintained schema definition?
- Migration scripts run faster than plain schema files
- It avoids the two definitions drifting apart, so the schema under test always matches what will actually reach production
- Separately maintained schema files are not supported by most databases
- Migration scripts automatically seed test data
Show answer
B. It avoids the two definitions drifting apart, so the schema under test always matches what will actually reach production
If the test schema is maintained by hand separately from the real migrations, the two can silently diverge over time, so a test could pass against a schema that no longer matches what production will actually run. Applying the real migrations guarantees the test schema is accurate.
5. When testing a stored procedure that transfers funds between two accounts and the transfer fails partway through, what must the test confirm beyond just catching the raised error?
- That the error message is phrased politely
- That the stored procedure can be called from any programming language
- That the source account's balance is completely unchanged, proving the whole operation rolled back
- That the destination account was created automatically
Show answer
C. That the source account's balance is completely unchanged, proving the whole operation rolled back
Proving atomicity requires checking that no partial update was left behind. Catching the error alone does not prove the first step of the transaction was undone; the test must re-query the source account and confirm its balance matches what it was before the failed attempt.