Discuss a project

Blog / Technologies

FastAPI dependency injection: testing it right

FastAPI provides a powerful tool for dependency injection (Dependency Injection) that is often underestimated when writing tests. Unlike Django or Flask, FastAPI makes it easy to replace real dependencies with mocks and fixtures. This makes testing the service layer almost transparent: you can isolate repositories, external APIs and even the database without changing the business logic.

We have already looked at how async affects Django 5 performance — here we will focus on FastAPI and its built-in dependency injection mechanism.

Dependency Injection in FastAPI works through the Depends mechanism. You declare that a function or class needs a particular dependency, and the framework takes care of providing it. If you create the dependency instance inside the function, the code becomes harder to test — you will have to use global state, mock global variables or override settings at the application level.

When Dependency Injection improves testability

Dependency Injection becomes truly useful when you have external or heavy dependencies. Think of a repository that works with a database, a client for an external API, or a SaaS authorization service. In an integration test or a load test you will want to replace them with fake implementations. Without DI you would have to either move all these dependencies into a global module, or build elaborate patterns such as Abstract Factory.

In FastAPI this can be done very elegantly. There are two approaches: either describe the dependency as an async def function with the appropriate annotation, or create a class with __call__ and register it through app.dependency_overrides. In the second case you get complete freedom: you can replace the class entirely, not just the returned value. This is useful when the dependency is not just "data" but a complex component with its own state or lifecycle.

Dependency Injection is not limited to swapping objects for tests. It also helps separate concerns in your code. Your endpoint becomes just a router that assembles ready-made components. Each component is responsible for its own task: the repository for working with the database, the validator for data validation, the email service for sending notifications. This approach makes the code more modular and easier to understand, and refactoring turns from drudgery into a pleasant task.

Managing the lifecycle of dependencies

By default, FastAPI creates dependencies anew for every request. If the same dependency appears several times in one request — for example, as a sub-dependency — its result is cached until the end of the request, and Depends(get_db, use_cache=False) turns that caching off. But caching within a request is not yet management of the application lifecycle. Heavy resources that must live as long as the application itself — a database connection pool, an external API client, a loaded ML model — are created in the lifespan handler and released when the service stops.

# main.py
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Runs once when the application starts
    app.state.engine = create_async_engine(os.environ["DATABASE_URL"])
    yield
    # Runs once when the application stops
    await app.state.engine.dispose()


app = FastAPI(lifespan=lifespan)

Lifecycle management is critically important for testing. When you create a dependency for a test, you want to control its state and be able to reset it between tests. With fixtures and dependency_overrides you can fully control which objects are used in tests and reset their state when necessary. This is especially important for components that keep state between calls.

So FastAPI has two levels of lifecycle management: dependencies created and cached within a single request, and lifespan for application-level resources. If a component only needs the request context — a database session, the current user — make it a dependency. If it is expensive and shared by all requests — create it in lifespan and get it through request.app.state. The split is simple, it is described in the official documentation and requires no additional libraries.

Complex Dependency Injection scenarios

Dependency Injection is especially powerful when dealing with complex scenarios. Imagine that you need to use different repositories depending on the context: for example, regular repositories in production and fake ones in tests that write to SQLite rather than Postgres. Or you need to choose a validation service dynamically depending on user settings. In both cases DI lets you do this very elegantly.

FastAPI lets you create dependencies that are functions of other dependencies. This lets you build hierarchies of dependencies and delegate responsibility to lower-level components. For example, you can create a dependency that gets the current user through a JWT token, and then use that dependency inside other dependencies to obtain the user's repository data. Such nesting keeps the code better organized.

Setting up the test environment with pytest and uv

Before moving on to writing tests, you need to set up the testing environment properly. The simplest way is to use uv for dependency management. It is a modern package manager that works much faster than pip and lets you precisely control the versions of all your project's dependencies. Installing the test dependencies takes a single command:

# Add the test dependencies to pyproject.toml or uv.lock
uv add --group dev pytest pytest-asyncio pytest-cov httpx asgi-lifespan "testcontainers[postgres]"

The pytest package is the main testing framework in Python. pytest-asyncio lets you write asynchronous tests with async def test_*. pytest-cov provides reports on test coverage of the code. httpx is an HTTP client for testing API endpoints that works asynchronously and emulates the behavior of real HTTP requests. testcontainers is a library for running real services (a database, Redis and so on) in Docker containers for integration tests.

So that pytest-asyncio picks up asynchronous tests and fixtures without unnecessary restrictions, enable auto mode in the pytest settings. Separately, it is worth mentioning the event_loop fixture that you will find in older articles: it has long been deprecated and has been removed in current versions of pytest-asyncio — the plugin's scope options are configured instead.

# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"

The pytest-testcontainers library is a convenient wrapper around testcontainers for pytest that automatically connects containers to fixtures. This greatly simplifies setup: you do not need to create and remove containers by hand, pytest does it for you. Thanks to this, integration tests become much simpler and more reliable.

# Install pytest-testcontainers
uv add --group dev pytest-testcontainers

Creating a pytest fixture for the application

The key step in setting up tests is a fixture that returns a test client ready to make requests. The application and its routes are declared at module level, and the fixture only replaces the dependencies and points them at test values. This guarantees that the tests are isolated and do not depend on the real configuration of the application.

# tests/conftest.py
import pytest
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient

from main import app


@pytest.fixture
async def client():
    from database import TestDatabase, get_db
    from repositories import UserRepository

    # Replace the dependencies with test implementations
    app.dependency_overrides[get_db] = TestDatabase.get_connection
    app.dependency_overrides[UserRepository] = TestDatabase.get_user_repository

    # LifespanManager runs the application's startup and shutdown logic,
    # which ASGITransport does not call by itself
    async with LifespanManager(app):
        transport = ASGITransport(app=app)
        async with AsyncClient(transport=transport, base_url="http://test") as ac:
            yield ac

    # Clear the overrides after the test finishes
    app.dependency_overrides.clear()
    await TestDatabase.cleanup()

In this example the fixture creates an AsyncClient with ASGITransport — requests go straight into the application, without the network. Since the transport does not run lifespan events, LifespanManager from the asgi-lifespan package takes care of that. get_db is overridden with a test version of the database that uses SQLite for fast and isolated tests, and UserRepository with a fake in-memory repository. After the test, the fixture clears the overrides and the test database.

Overriding dependencies for unit tests

For unit tests you do not need to override the whole application. It is enough to mock the dependencies inside the tests themselves. unittest.mock.patch or pytest's monkeypatch works for this. It is convenient when you want to override specific components for one or several tests.

# tests/test_users.py
import pytest
from httpx import AsyncClient
from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
async def test_create_user_with_validation(client: AsyncClient):
    # Create a fake validator
    fake_validator = AsyncMock()
    fake_validator.validate.return_value = None

    # Override the validator for this test
    with patch("services.UserService.validate", fake_validator):
        response = await client.post(
            "/users",
            json={"email": "test@example.com", "name": "Test User"},
        )

    assert response.status_code == 200
    assert response.json()["email"] == "test@example.com"

@pytest.mark.asyncio
async def test_create_user_invalid_email(client: AsyncClient):
    response = await client.post(
        "/users",
        json={"email": "invalid-email", "name": "Test User"},
    )
    assert response.status_code == 422

This example uses unittest.mock.patch to override specific functions. The fake validator replaces the real validation logic, letting you test the business logic without real checks. This is a typical approach for unit tests: isolate and test a specific component without touching other parts of the system.

Integration tests with testcontainers

Integration tests are tests that check how all the components of the system work together. For them it is better to use real components rather than mocks. testcontainers lets you start a real database (Postgres, MySQL, MongoDB), Redis or another service in a Docker container, connect to it and test the whole stack from the database to the API.

# tests/integration/test_users.py
import os

import pytest
import pytest_asyncio
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from db.base import get_db
from main import app
from models import Base

# The module's tests and fixtures run in one module-level event loop
pytestmark = pytest.mark.asyncio(loop_scope="module")


@pytest_asyncio.fixture(loop_scope="module", scope="module")
async def db_engine():
    from testcontainers.postgres import PostgresContainer

    # In CI the database is started as a service and comes in through DATABASE_URL,
    # locally we start a PostgreSQL container through testcontainers
    db_url = os.environ.get("DATABASE_URL")
    if db_url:
        engine = create_async_engine(db_url)
    else:
        with PostgresContainer("postgres:15", driver="asyncpg") as postgres:
            engine = create_async_engine(postgres.get_connection_url())

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await engine.dispose()


@pytest_asyncio.fixture(loop_scope="module")
async def client(db_engine):
    TestSessionLocal = sessionmaker(bind=db_engine, class_=AsyncSession, expire_on_commit=False)

    async def override_get_db():
        async with TestSessionLocal() as session:
            yield session

    # Override the dependency so that requests go to the test database
    app.dependency_overrides[get_db] = override_get_db

    async with LifespanManager(app):
        transport = ASGITransport(app=app)
        async with AsyncClient(transport=transport, base_url="http://test") as ac:
            yield ac

    # Clear the overrides
    app.dependency_overrides.clear()


@pytest.mark.integration
async def test_create_user_integration(client: AsyncClient):
    response = await client.post(
        "/users",
        json={"email": "integration@example.com", "name": "Integration Test"},
    )
    assert response.status_code == 200
    assert response.json()["email"] == "integration@example.com"

    # Check that the user is really saved in the database
    response = await client.get(f"/users/{response.json()['id']}")
    assert response.json()["email"] == "integration@example.com"

Here the db_engine fixture lives at module level: the database is created once and dropped after all the tests. Locally a PostgreSQL container is started through testcontainers, while in CI it is enough to pass DATABASE_URL — and no container is needed. All tables are created from the SQLAlchemy models, requests go through the overridden get_db dependency, and the loop_scope="module" marker keeps the tests and fixtures in one event loop. This keeps the test environment clean and isolated.

Configuring pytest for different types of tests

pytest makes it easy to separate unit tests from integration tests using markers. You can tag tests with special labels and run them separately. This is especially useful in CI/CD when you want to run only unit tests on every commit, and integration tests less often, for example only when separate pipelines are started or only for critical changes.

# Run only unit tests (fast)
uv run pytest -m "not integration" --cov=. --cov-report=html

# Run only integration tests (slow)
uv run pytest -m integration --cov=. --cov-report=html

# Run all tests
uv run pytest --cov=. --cov-report=html

# Run tests from a specific file
uv run pytest tests/unit/test_users.py

# Run tests with detailed output
uv run pytest -v --log-cli-level=INFO

These are the standard commands for running tests. The -m flag filters tests by markers. The --cov flag turns on code coverage measurement and produces a report in HTML format. You can add these commands to a Makefile to make running tests easier for new developers.

# Makefile
.PHONY: test unit integration clean test-coverage

test:
    uv run pytest

unit:
    uv run pytest -m "not integration"

integration:
    uv run pytest -m integration

test-coverage:
    uv run pytest --cov=. --cov-report=html
    open htmlcov/index.html

clean:
    rm -rf .pytest_cache htmlcov

CI/CD configuration with GitLab CI

To run tests automatically in CI/CD you can use GitLab CI or another CI/CD service. GitLab CI uses a configuration file .gitlab-ci.yml in the root of the repository. In this file you define jobs (tasks) that run on commits and MRs. For FastAPI projects you can set up jobs that run unit tests on every commit and MR, and integration tests less often, only for the main branch.

# .gitlab-ci.yml
stages:
  - test

# Job for running unit tests
unit-tests:
  stage: test
  image: python:3.11-slim
  before_script:
    # Install uv for Linux
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - export PATH="$HOME/.local/bin:$PATH"
    # Install the dependencies
    - uv sync --frozen --all-extras
  script:
    - uv run pytest -m "not integration" --cov=. --cov-report=html --cov-report=xml
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml
    paths:
      - htmlcov/
  coverage: '/TOTAL.*? (100|\d{1,3})\%/'
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH == "main"'

# Job for integration tests (runs less often)
integration-tests:
  stage: test
  image: python:3.11-slim
  # PostgreSQL is started as a service and is available at the host postgres
  services:
    - postgres:15
  variables:
    POSTGRES_PASSWORD: "test"
    POSTGRES_USER: "test"
    POSTGRES_DB: "test"
    POSTGRES_HOST_AUTH_METHOD: trust
    DATABASE_URL: "postgresql+asyncpg://test:test@postgres:5432/test"
  before_script:
    - curl -LsSf https://astral.sh/uv/install.sh | sh
    - export PATH="$HOME/.local/bin:$PATH"
    - uv sync --frozen --all-extras
  script:
    - uv run pytest -m integration --cov=. --cov-report=xml
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml
  coverage: '/TOTAL.*? (100|\d{1,3})\%/'
  only:
    - merge_requests
    - main

This example configures two jobs: unit-tests and integration-tests. Unit tests run for every commit and MR. The integration tests use PostgreSQL as a service: it is started next to the job and is available at the host postgres, while the tests read DATABASE_URL. Both jobs produce HTML coverage reports and XML reports for GitLab Code Coverage.

CI/CD with GitHub Actions

If you use GitHub instead of GitLab, you can set up a similar process with GitHub Actions. GitHub Actions uses the file .github/workflows/test.yml to define jobs and run tests. An example configuration for a FastAPI project looks like this:

# .github/workflows/test.yml
name: Tests

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install uv
        run: curl -LsSf https://astral.sh/uv/install.sh | sh

      - name: Install dependencies
        run: uv sync --frozen --all-extras

      - name: Run unit tests
        run: uv run pytest -m "not integration" --cov=. --cov-report=html --cov-report=xml

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          file: ./coverage.xml
          flags: unit-tests

  integration-tests:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: test
          POSTGRES_USER: test
          POSTGRES_DB: test
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install uv
        run: curl -LsSf https://astral.sh/uv/install.sh | sh

      - name: Install dependencies
        run: uv sync --frozen --all-extras

      - name: Run integration tests
        env:
          DATABASE_URL: postgresql+asyncpg://test:test@localhost:5432/test
        run: uv run pytest -m integration --cov=. --cov-report=xml

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v4
        with:
          file: ./coverage.xml
          flags: integration-tests

GitHub Actions automatically runs unit tests for every commit and MR. The integration tests use PostgreSQL as a service and run only for changes to critical branches. Both jobs produce code coverage reports and automatically upload them to Codecov for visualization and monitoring. This makes CI/CD pipelines highly reliable and lets you spot regressions quickly.

Best practice: isolating the test environment

One of the most important practices is isolating the test environment. Every test should run in an isolated environment that does not affect other tests and leaves no changes behind. testcontainers and fixtures guarantee this, but it is also important to make sure that no temporary files, database contexts or other state are left over after the tests. pytest removes fixtures automatically, but you have to control what is created inside each test.

For the database this is especially important. Every integration test should start with a clean database. The simplest way is to run TRUNCATE or DELETE on all tables before each test, or to use db.session.rollback() after each test to roll back all changes. This guarantees that tests do not affect each other and do not accumulate changes in the database.

For HTTP requests it is important not to use the same HTTP client for several tests that depend on state. It is better to create a new client for every test or to use a fixture that creates a clean client before each test. This guarantees that state from one test does not affect other tests.

Debugging tests and local development

pytest provides many debugging tools. The -s flag prints stdout/stderr inside tests, which is useful for debugging when you need to see intermediate results. The -vv flag gives more detailed output about each test, including the output of fixtures and dependencies. You can also use pytest-xdist to run tests in parallel across several workers, which speeds up runs in large projects.

# Run with stdout output
uv run pytest -s -v

# Run tests in parallel
uv run pytest -n auto

# Run a specific test
uv run pytest tests/unit/test_users.py::test_create_user

# Debug with pdb
uv run pytest --pdb

To debug API tests you can use httpx or TestClient with the requests and responses printed. This helps you understand what data is passed to the endpoint and what is returned. You can also use print or logging inside tests to output debugging information.

Integration tests are well complemented by a contract-based approach: if the API is described by a schema in advance, the checks rely on a single source of truth. We have written about how to design an API schema before code and keep the contract under control.

Conclusion

FastAPI Dependency Injection is not just architectural refinement, but a practically necessary tool for writing testable code. It turns chaotic dependency injection into a structured process. Use it seriously: testability goes up sharply, while the time spent writing tests goes down. When you can easily replace any dependency, you start writing modular code that does not break from external changes.

Testability is not a requirement but the result of choosing the right architecture. Dependency Injection in FastAPI helps make that choice deliberate and well-founded. It lets you write code that is not tied to a specific implementation, that is easy to change, that is simpler to extend and that breaks less often. All of this makes development more efficient and more enjoyable.

Using pytest, uv, testcontainers and CI/CD turns testing into a standard part of development. New developers can quickly set up the environment and start writing tests thanks to simple instructions and FastAPI's auto-generated documentation. High test coverage and automatic runs in CI/CD ensure that your code will be reliable and stable.

Shall we discuss your project?

Tell us about your task and we will come back with an estimate of the time and the cost within two working days.