Skip to content

Back-end testing: unit, integration, contract, load and security (2026 guide)

A real database with Testcontainers, when to mock, API tests, contracts with Pact, load with k6, security, mutation and testing in production, with examples.

Ramon Gomes 19 min read Level: Intermediate

Also available in: Español, Français, Português

The API for this site has 14 unit test files and 9 integration ones. The integration tests start the application, make real HTTP requests and write to a test Postgres, which is emptied before each case. And there is a guard that has already saved me: if the DATABASE_URL variable does not have _test in the database name, the suite refuses to run. A TRUNCATE on the wrong database would be the end of the blog.

That is the kind of detail that separates back-end testing from front-end testing. Here, the damage from a mistake is lost data, a double charge or an open endpoint. In this guide I go through the types of server tests, with examples in Node and mentions of Python, Java and Go, and point to the tools and books worth your time. If you care about the interface, the front-end testing guide is the companion to this one.

Three-panel comic: a cook tastes the sauce and grimaces, the head chef inspects the plated dish with a magnifying glass, and on a packed Friday the cook juggles six pans while tickets fly around
Tasting the sauce is the unit test. Checking the assembled plate is integration. The packed Friday night is the load test.

What Changes When Testing the Back-end

On the front-end, almost everything that matters happens on the screen. On the back-end, what matters is at the edges: the database, the queue, another team's API, the clock, the payment gateway. That is where the expensive bug lives, and it is exactly what a badly designed test swaps for a mock.

The book Software Engineering at Google separates two ideas that help you think about this (abseil.io):

  • Size: how many resources the test uses. Small runs in a single process, with no network or disk. Medium can use several processes and network only to localhost, like a database in a containerIsolated package that bundles an application with its dependencies and runs the same on any machine, sharing the host operating system. Docker is the most common.. Large can involve several machines.
  • Scope: how much code the test validates, from one function to a whole system.

An integration test with Postgres in a container is medium in size and can be narrow in scope. Thinking this way ends the "integration is slow" argument: it depends on what you start up.

The Types of Back-end Tests

Type What it checks Common tools
Unit Isolated business rule: shipping calculation, validation, state machine Vitest, Jest, node:test, pytest, JUnit, testing (Go)
Integration Your code with a real dependency: database, queue, cache Testcontainers, disposable test database
API (component) One HTTP route end to end inside the service Supertest, TestClient (FastAPI), MockMvc (Spring)
Contract Whether what the consumer expects matches what the provider delivers Pact, Schemathesis
Load Behavior under volume: response time, errors, bottlenecks k6, Gatling, Locust, JMeter
Security Vulnerabilities in the code, in the dependencies and in the running API OSV-Scanner, Snyk, npm audit, OWASP ZAP
Mutation Whether the tests catch real defects Stryker, PIT, mutmut
Production Whether what was published is up and healthy Post-deploy smoke, canary, synthetic monitoring
Diagram with the six back-end test layers: unit, integration, API, contract, load and security, and production
The integration layer, with a real database, is the one that protects a typical API the most.

Pyramid or honeycomb? Ham Vocke's practical test pyramid says to push each test down to the lowest possible level. Spotify, looking at microservices, proposed the honeycomb: most tests should be integration tests, testing the service through its API, with few tests of implementation details and, ideally, no test that depends on another service being correct (Spotify). Spotify itself admits the cost: the tests take seconds instead of milliseconds. For a service that is basically "receive HTTP, validate, write to the database", the honeycomb usually wins.

Unit Tests: Business Rules Without a Database

The unit test is the place for logic with many cases: calculation, validation, conversion, discount rules. It does not open a connection, does not read a file and does not wait on the clock.

The biggest enemy of unit tests on the back-end is time. Code that calls new Date() in the middle of a rule becomes a test that fails at midnight or on the last day of the month. The way out is to inject the clock:

ts
// dueDate.ts
export function dueIn(days: number, now: () => Date = () => new Date()): Date {
  const date = now()
  date.setUTCDate(date.getUTCDate() + days)
  return date
}

// dueDate.test.ts
import { test, expect } from 'vitest'
import { dueIn } from './dueDate'

test('adds the days starting from the injected clock', () => {
  const now = () => new Date('2026-01-30T12:00:00Z')
  expect(dueIn(3, now).toISOString()).toBe('2026-02-02T12:00:00.000Z')
})

When you cannot inject it, every runner has a fake clock: vi.useFakeTimers() in Vitest, mock.timers in Node's native test runner (Node.js), time-machine or freezegun in Python, and testing/synctest in Go starting with version 1.25 (Go).

In Node, the three serious runner options are Vitest (fast, great with TypeScript and ESM), Jest (mature, comes built into NestJS) and node:test, which is native, stable since Node 20 and needs no dependencies at all. For a small library, the native one is enough.

Test Doubles: Stub, Mock, Fake and Spy

"Mock" became a generic name, but Gerard Meszaros, in the book xUnit Test Patterns, separated five kinds of test double, and Martin Fowler made the list popular (Martin Fowler):

Double What it does Example
Dummy Only fills the place of a parameter A logger nobody reads
Stub Returns a canned answer Dollar exchange rate fixed at 5.00
Spy A stub that also records how it was called Counts how many emails "were sent"
Mock Comes programmed with expectations and fails if they are not met "Must call charge once with R$ 100"
Fake A working implementation with a shortcut In-memory repository instead of Postgres

The question that matters is when to use them. Vladimir Khorikov gives the clearest rule I know: only replace with mocks the unmanaged dependencies, the ones other systems can also see, like an SMTP server, a shared queue or a partner's API. A database that only your application uses is a managed dependency: use the real one (Khorikov).

Google's book goes in the same direction, with an order of preference: the real implementation, if it is fast and deterministic; then a fake; then a stub; and only last an interaction test ("was called with this argument") (abseil.io). Interaction tests break on every refactor, because they check how the code does something, not what it does.

Integration Tests with a Real Database

For years the excuse for not using a real database was "it is a pain to start one". Testcontainers killed that excuse: the test itself starts a Postgres (or Redis, Kafka, RabbitMQ) in a Docker container, uses it and throws it away. There are libraries for Node, Java, Python, Go, .NET and a dozen more languages, and the Thoughtworks Technology Radar put it in "Adopt", its strongest recommendation, calling it a useful default option for a reliable test environment (Thoughtworks, in Portuguese).

ts
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from '@testcontainers/postgresql'
import { Client } from 'pg'
import { beforeAll, afterAll, beforeEach, afterEach, test, expect } from 'vitest'

let pg: StartedPostgreSqlContainer
let db: Client

beforeAll(async () => {
  pg = await new PostgreSqlContainer('postgres:17-alpine').start() // pin the production version
  db = new Client({ connectionString: pg.getConnectionUri() })
  await db.connect()
  await db.query('create table customers (id int primary key, name text not null)')
}, 60_000) // the first image download takes a while

afterAll(async () => { await db.end(); await pg.stop() })
beforeEach(() => db.query('BEGIN'))
afterEach(() => db.query('ROLLBACK')) // every test starts clean

test('name is required, and the database is what enforces it', async () => {
  await expect(db.query('insert into customers (id) values (1)')).rejects.toThrow()
})

Three precautions I learned in practice:

  • Same version as production. Swapping Postgres for SQLite or H2 in tests is asking for a false green: the dialect is different. Vocke calls this "a risky business".
  • Rollback only works on the same connection. If the code uses a pool, each query can go to a different connection, outside the test's transaction. Then the way out is a TRUNCATE before each case (which is what I do here) or the Testcontainers snapshot.
  • Never run the suite against the production database. It sounds obvious until the day someone runs it with the wrong .env. A guard in the setup that checks the database name costs three lines.

In Python, SQLAlchemy's official testing pattern is to open an outer transaction and create the session with join_transaction_mode="create_savepoint", rolling back at the end (SQLAlchemy). Django does this on its own: TestCase runs each test inside a transaction and creates a test_ database that is destroyed at the end (Django). In Spring Boot, @ServiceConnection wires the container into the context without configuring a URL (Spring).

Testing the HTTP API

An API test starts the application in memory and makes real requests, going through routing, validation, authentication, service and database. In Node, Supertest does this without taking a port: if the server is not listening, it binds to a temporary port on its own (Supertest).

ts
import request from 'supertest'
import { test, expect } from 'vitest'
import { createApp } from '../src/app'

test('POST /orders rejects zero quantity with 422', async () => {
  const app = createApp()

  const res = await request(app)
    .post('/orders')
    .send({ sku: 'ABC', quantity: 0 })

  expect(res.status).toBe(422)
  expect(res.body.error).toMatch(/quantity/i)
})

Also test what should not work: a request with no token, another user's token, an extra field in the body. The most common flaw in APIs, according to the OWASP API Security Top 10, is object-level authorization: user A changes the ID in the URL and reads user B's order (OWASP). An integration test with two users catches it in seconds.

A classic trap: exporting the app with app.listen() already called. The test leaves the server open and the runner never finishes. Separate creating the app (createApp) from the file that starts the server.

The Same Idea in Python, Java and Go

Language Runner Real database Mocks and data
Python pytest (fixtures, parametrize) testcontainers-python, transaction with savepoint pytest-mock, factory_boy, Faker
Java JUnit 6 Testcontainers + @ServiceConnection in Spring Boot Mockito, AssertJ
Go testing package, table-driven tests with t.Run testcontainers-go go.uber.org/mock (the old golang/mock was archived)
Node Vitest, Jest, node:test Testcontainers MSW or nock for outgoing HTTP, Faker

Two details that catch a lot of people: in pytest-asyncio, the default mode is strict, and an async def test without @pytest.mark.asyncio does not run the way you expect (pytest-asyncio). And in testcontainers-python, if you do not specify the image, it uses postgres:latest: pin the version.

Contract Tests

When the front-end or another service consumes your API, each side tests against its own mock, and both mocks can drift away from reality. The contract test closes that gap.

  • Pact is consumer-driven: the consumer's tests generate a contract file with the requests it makes and the responses it expects, and the provider runs that contract against the real code (Pact). The docs are honest about when not to use it: public APIs, partners who will not adopt Pact, a BFFServer layer built for one specific interface: it combines calls to several services, keeps tokens away from the browser and returns data shaped for the screen. that only passes calls through, and load testing (Pact).
  • Schemathesis reads your OpenAPI (or GraphQL) schema and generates hundreds of requests automatically, looking for 500 errors, responses that do not match the schema and even access to another user's objects. For each failure, it gives you a minimal curl that reproduces it (Schemathesis).
bash
uvx schemathesis run ./openapi.yaml --url http://localhost:8000

If you come across a Dredd tutorial, know that the project was archived in November 2024. Do not start anything new with it.

Load and Performance Testing

Load testing answers "how much can it take" before Black Friday answers it for you. The k6 docs organize the types (Grafana):

  • Smoke: minimal load, just to see whether the script and the system work. Always start with it.
  • Average load: a normal day's traffic.
  • Stress: above normal, to see how it degrades.
  • Soak: normal load for hours, to find memory and connection leaks.
  • Spike: a sudden peak, like a campaign that goes viral.
  • Breakpoint: ramps up until it breaks, to find the limit.

k6 lets you write the scenario in JavaScript or TypeScript and has thresholds: if the 95th percentile of response time goes over the limit, the process exits with an error and CI fails.

js
import http from 'k6/http'
import { check, sleep } from 'k6'

export const options = {
  stages: [
    { duration: '1m', target: 20 }, // ramp up to 20 users
    { duration: '3m', target: 20 }, // hold
    { duration: '1m', target: 0 },  // ramp down
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],   // less than 1% errors
    http_req_duration: ['p(95)<300'], // 95% under 300 ms
  },
}

export default function () {
  const res = http.get('https://staging.example.com/api/products')
  check(res, { 'status 200': (r) => r.status === 200 })
  sleep(1)
}

k6 has been on version 2 since May 2026, which removed commands like k6 login: an old tutorial may not work (k6). Active alternatives: Gatling (Java or JS/TS, complex scenarios), Locust (scenarios in Python) and JMeter (graphical interface and lots of protocols, but no new release since January 2024).

Security Testing

Back-end security has three fronts, and none of them covers the others:

  • Dependencies (SCA). npm audit, OSV-Scanner (from Google, using the OSV.dev database) and Snyk compare your lockfile against vulnerability databases. Be careful with npm audit fix --force: it installs major versions and can break the application (npm).
  • Code (SAST). Static analysis finds dangerous patterns, like SQL built from user text. OWASP itself warns that it produces lots of false positives and struggles with authentication and access control (OWASP).
  • Running application (DAST). OWASP ZAP attacks the published API in a test environment. The baseline mode is passive, takes a few minutes and fits in CI (ZAP):
bash
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.com

None of these tools knows that user A cannot see user B's order. That authorization test is yours to write, and it is the most important one on the list.

Mutation Testing and Property-based Testing

Mutation testing answers the question coverage does not: do my tests catch bugs? The tool changes the code on purpose (swaps > for >=, + for -, deletes a line) and runs the suite. If some test fails, the "mutant" was killed. If they all pass, it survived, and you found a gap (Stryker). Google runs mutation testing in code review, only on the changed lines, with more than 24,000 developers in the evaluation (arXiv). The tools are Stryker (JS/TS, C#, Scala), PIT (Java) and mutmut (Python). Running it on everything on every commit is expensive: use incremental mode or run it only on the PR's files.

Property-based testing flips the game: instead of picking examples, you describe a rule that holds for any input, and the library generates hundreds of inputs trying to break it. It works very well for parsers, serialization and calculations. In JS, fast-check; in Python, Hypothesis.

ts
import { test, expect } from 'vitest'
import fc from 'fast-check'

test('saving and reading back returns the same order', () => {
  fc.assert(
    fc.property(fc.record({ id: fc.integer(), customer: fc.string() }), (order) => {
      expect(JSON.parse(JSON.stringify(order))).toEqual(order)
    }),
  )
})

Swap fc.integer() for fc.double() and the test fails: NaN and -0 do not survive the round trip through JSON. That is exactly the kind of case nobody remembers to write by hand.

Testing in Production

No test environment is the same as production. That is why the last layer happens after deploy:

  • Post-deploy smoke: half a dozen checks right after publishing (the API responds, login works, the database connects). If it fails, the pipeline rolls back.
  • Canary: the new version goes to a small slice of traffic and is compared with the old one at the same time. Google's SRE Workbook recommends one canary at a time, few metrics, around a dozen at most, and comparing against a simultaneous control group, not against "before" (Google SRE).
  • Feature flags: ship it turned off and turn it on gradually. For testing, run the production configuration and the same one with the new flags turned off; you do not need to test every combination (Martin Fowler).
  • Synthetic monitoring: a bot repeats the main journey every few minutes and alerts you when it breaks.
  • Chaos engineering: taking a piece down on purpose to see whether the system holds up. It only makes sense with good observability and a well-defined "normal" state, starting with a small blast radius (Principles of Chaos).

It is also worth testing migrations: apply all of them to a clean database in CI, run the suite on top and use a linter like Squawk, which warns you when a migration is going to lock the table in production (Squawk).

TDD: When It Is Worth It

TDD (test-driven development) means writing the test before the code. Kent Beck, who popularized the practice, published the "canonicalAddress a page declares as the official version of its content, so search engines merge duplicates and index only that one." version in 2023: make a list of tests, turn one item into a failing test, make it pass, refactor if needed and repeat (Kent Beck). Among the mistakes he lists: writing all the tests before making the first one pass, and copying the value the code computed into the assertion.

In my experience, TDD pays off a lot for business rules with clear cases and for bug fixes (the test that reproduces the bug comes first). It pays off little for exploratory code and framework glue. DORA recommends the practice (DORA), but it is not a religion: what matters is that the test exists before the merge.

Where to Start

  1. Separate the rule from the transport. Business logic in functions that know nothing about HTTP or the database. They get cheap unit tests.
  2. Start a real test database with Testcontainers or Docker Compose, plus a guard that stops the suite from running anywhere else.
  3. Write API tests for the critical routes, including the cases that should fail: no token, another user's token, invalid data.
  4. Put SCA in CI (npm audit or OSV-Scanner) and a ZAP baseline against staging.
  5. Before a launch, run a load test with k6, starting with the smoke test.
  6. After every deploy, run a smoke test against production.
  7. Once the suite is stable, try mutation testing on the most critical modules to find the gaps.

Read and Watch More

In Portuguese:

In English:

Books:

  • Unit Testing: Principles, Practices, and Patterns, Vladimir Khorikov (Manning, 2020). The best book on when to use mocks and what to test. The examples are in C#, but they apply to any language.
  • Test-Driven Development: By Example, Kent Beck (Addison-Wesley, 2002). The classic.
  • Working Effectively with Legacy Code, Michael Feathers (Prentice Hall, 2004). How to put tests on code that was not built to be tested.
  • Test-Driven Development: Teste e Design no Mundo Real, Mauricio Aniche (Casa do Código), in Portuguese. Written by a Brazilian who is now a reference in testing.
  • Growing Object-Oriented Software, Guided by Tests, Steve Freeman and Nat Pryce (Addison-Wesley, 2009). The "London school" view, which uses mocks to design the system. Good for understanding the other side.
  • xUnit Test Patterns, Gerard Meszaros (Addison-Wesley, 2007). The encyclopedia where the names of the test doubles come from.
  • Release It!, Michael Nygard (Pragmatic Bookshelf, 2nd edition in 2018). About what breaks in production and how to prepare for it.

Frequently Asked Questions

What is the difference between a mock and a stub?

A stub only returns a canned answer, and the test checks the result. A mock comes with expectations about how it will be called, and the test fails if the call does not happen as expected. When in doubt, prefer a stub and check the final state.

Should I use a real database in my tests?

For a database that only your application uses, yes. With Testcontainers, it starts in seconds and catches what no mock does: constraints, transactions, SQL and migrations.

Are integration tests too slow to run all the time?

They do not have to be. Start the container once per file or per suite, isolate the cases with a transaction or TRUNCATE and run in parallel by file. A suite of hundreds of integration tests fits in a few minutes.

Do I need load testing in every project?

No. It is worth it before a launch, a campaign or when traffic is about to change scale. For an internal system with twenty users, a load smoke test already answers the question.

What is the difference between a contract test and an API test?

An API test checks whether your route does what it should. A contract test checks whether it keeps delivering what the consumer expects. A change can pass the first and break the second.

References

Source: https://ramongomessilva.com.br/blog/back-end-testing-guide · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Back-end testing: unit, integration, contract, load and security (2026 guide). Ramon Gomes, 10 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/back-end-testing-guide. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 10). Back-end testing: unit, integration, contract, load and security (2026 guide). Ramon Gomes. https://ramongomessilva.com.br/blog/back-end-testing-guide

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026backendtesting,
  author = {Gomes, Ramon},
  title = {{Back-end testing: unit, integration, contract, load and security (2026 guide)}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-10},
  url = {https://ramongomessilva.com.br/blog/back-end-testing-guide},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles