Python

Testing FastAPI Applications with Pytest: Unit Tests, Integration Tests, and Mocking

Testing is an essential part of building reliable FastAPI applications. Whether you're developing a small REST API or a production backend with authentication,…

D
DevByteTechnical Author
Published
16 min read3 views
Testing FastAPI Applications with Pytest: Unit Tests, Integration Tests, and Mocking

Testing is an essential part of building reliable FastAPI applications. Whether you're developing a small REST API or a production backend with authentication, database operations, and external service integrations, automated tests help you catch bugs before they reach production.

FastAPI makes testing straightforward with its TestClient, while Pytest provides a flexible framework for organizing and executing tests. You can test individual functions, validate API endpoints, simulate database interactions, and mock external services without making real network requests.

In this guide, we'll build a practical testing setup for a FastAPI application and explore unit testing, integration testing, dependency overrides, mocking, asynchronous tests, and coverage.

1. Why Test FastAPI Applications?

Imagine you're building an API for managing users. It supports creating users, retrieving user details, validating email addresses, and checking whether a user already exists.

Without automated tests, you might manually check every endpoint after each code change. This becomes time-consuming as your application grows.

Automated tests help you:

  • Detect regressions when modifying existing code.

  • Validate request and response structures.

  • Verify authentication and authorization behavior.

  • Test database interactions and error handling.

  • Simulate external API failures.

  • Refactor application logic with greater confidence.

A well-tested application typically uses multiple testing levels:

Testing Type

Purpose

Example

Unit testing

Tests individual functions or components

Validate email or calculate a discount

Integration testing

Tests how multiple components work together

Create a user through an API endpoint

API testing

Validates HTTP requests and responses

Check status codes and response JSON

Mocking

Replaces real dependencies with controlled substitutes

Simulate an external payment API

End-to-end testing

Tests a complete workflow across relevant systems

Register a user and retrieve their profile

These testing approaches complement one another. Unit tests are usually fast and focused, while integration tests help verify that the application's components work correctly together.

2. Setting Up the Testing Environment

First, install FastAPI, Uvicorn, Pytest, and the HTTP client dependencies required for testing.

pip install fastapi uvicorn pytest httpx

For asynchronous endpoint tests, install the asynchronous testing support provided by AnyIO:

pip install anyio

If your project uses SQLAlchemy with a PostgreSQL database, you may also need your database driver and SQLAlchemy dependencies.

A simple project structure could look like this:

fastapi-testing/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── schemas.py
│   └── services.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   ├── test_services.py
│   └── test_api.py
└── requirements.txt

This structure separates application code from tests, making the project easier to maintain as it grows.

3. Building a Simple FastAPI Application

Before writing tests, let's create a small application that manages users.

Create app/schemas.py:

from pydantic import BaseModel, EmailStr, Field


class UserCreate(BaseModel):
    name: str = Field(min_length=2, max_length=100)
    email: EmailStr


class UserResponse(BaseModel):
    id: int
    name: str
    email: EmailStr

The UserCreate schema validates incoming requests, while UserResponse defines the structure of the data returned to clients.

Because EmailStr requires an additional dependency, install it:

pip install email-validator

Now create app/services.py:

from app.schemas import UserCreate


class UserService:
    def __init__(self):
        self.users = []
        self.next_id = 1

    def create_user(self, user: UserCreate):
        for existing_user in self.users:
            if existing_user["email"] == str(user.email):
                raise ValueError("Email already registered")

        new_user = {
            "id": self.next_id,
            "name": user.name,
            "email": str(user.email),
        }

        self.users.append(new_user)
        self.next_id += 1

        return new_user

    def get_user(self, user_id: int):
        for user in self.users:
            if user["id"] == user_id:
                return user

        return None

This service provides two operations:

  • create_user() creates a user and prevents duplicate email addresses.

  • get_user() returns a user by ID or None if the user does not exist.

Important: This example stores users in memory to keep the testing concepts simple. Data disappears when the application restarts, and this implementation is not suitable for production. A real application would use a database and enforce uniqueness at the database level as well.

Next, create app/main.py:

from fastapi import FastAPI, Depends, HTTPException, status

from app.schemas import UserCreate, UserResponse
from app.services import UserService

app = FastAPI(title="User Management API")

user_service = UserService()


def get_user_service():
    return user_service


@app.post(
    "/users",
    response_model=UserResponse,
    status_code=status.HTTP_201_CREATED,
)
def create_user(
    user: UserCreate,
    service: UserService = Depends(get_user_service),
):
    try:
        return service.create_user(user)
    except ValueError as exc:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=str(exc),
        )


@app.get("/users/{user_id}", response_model=UserResponse)
def get_user(
    user_id: int,
    service: UserService = Depends(get_user_service),
):
    user = service.get_user(user_id)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found",
        )

    return user

Notice that the application retrieves its service through a dependency function.

This is useful for testing because FastAPI allows you to override dependencies. Tests can provide a separate service instance instead of using the application's shared instance.

4. Understanding Pytest Basics

Pytest is a Python testing framework that automatically discovers test files and functions using naming conventions.

By default, Pytest looks for files such as:

test_example.py
example_test.py

Test functions usually begin with test_:

def test_addition():
    assert 2 + 3 == 5

The assert statement checks whether a condition is true. If it isn't, Pytest reports a failure with information about the expected and actual results.

Run your tests using:

pytest

For more detailed output, use:

pytest -v

To execute a particular test file:

pytest tests/test_services.py -v

You can also stop after the first failure:

pytest -x

These options are especially useful when working with larger test suites.

5. Writing Unit Tests for Business Logic

Unit tests focus on small pieces of code without sending HTTP requests or depending on the entire application.

Let's test the UserService independently.

Create tests/test_services.py:

import pytest

from app.schemas import UserCreate
from app.services import UserService


@pytest.fixture
def user_service():
    return UserService()


def test_create_user(user_service):
    user = UserCreate(
        name="Manjeet",
        email="manjeet@example.com",
    )

    result = user_service.create_user(user)

    assert result["id"] == 1
    assert result["name"] == "Manjeet"
    assert result["email"] == "manjeet@example.com"


def test_get_existing_user(user_service):
    user = UserCreate(
        name="Rahul",
        email="rahul@example.com",
    )

    created_user = user_service.create_user(user)

    result = user_service.get_user(created_user["id"])

    assert result is not None
    assert result["name"] == "Rahul"


def test_get_nonexistent_user(user_service):
    result = user_service.get_user(999)

    assert result is None


def test_duplicate_email_raises_error(user_service):
    user = UserCreate(
        name="Rahul",
        email="rahul@example.com",
    )

    user_service.create_user(user)

    with pytest.raises(
        ValueError,
        match="Email already registered",
    ):
        user_service.create_user(user)

Understanding the tests

The first test checks that a user is created with the expected values.

The second creates a user and retrieves it by ID.

The third verifies that an unknown ID returns None.

The fourth checks that duplicate emails raise the expected exception.

We also use a Pytest fixture:

@pytest.fixture
def user_service():
    return UserService()

A fixture prepares reusable test dependencies. Pytest automatically supplies the fixture to any test function that requests it as an argument.

Because this fixture creates a new service instance for each test, the tests don't share user data.

This isolation is important: one test should not unexpectedly pass or fail because another test changed shared state.

6. Testing API Endpoints with TestClient

Unit tests verify business logic, but they don't test the complete HTTP request and response behavior.

FastAPI provides TestClient, which lets you send requests to your application without starting a separate web server.

Create tests/test_api.py:

import pytest
from fastapi.testclient import TestClient

from app.main import app, get_user_service
from app.services import UserService


@pytest.fixture
def client():
    test_service = UserService()

    app.dependency_overrides[get_user_service] = (
        lambda: test_service
    )

    with TestClient(app) as test_client:
        yield test_client

    app.dependency_overrides.clear()


def test_create_user_api(client):
    response = client.post(
        "/users",
        json={
            "name": "Manjeet",
            "email": "manjeet@example.com",
        },
    )

    assert response.status_code == 201

    data = response.json()

    assert data["id"] == 1
    assert data["name"] == "Manjeet"
    assert data["email"] == "manjeet@example.com"


def test_get_user_api(client):
    create_response = client.post(
        "/users",
        json={
            "name": "Rahul",
            "email": "rahul@example.com",
        },
    )

    user_id = create_response.json()["id"]

    response = client.get(f"/users/{user_id}")

    assert response.status_code == 200
    assert response.json()["name"] == "Rahul"


def test_get_missing_user_api(client):
    response = client.get("/users/999")

    assert response.status_code == 404
    assert response.json()["detail"] == "User not found"


def test_create_user_with_invalid_email(client):
    response = client.post(
        "/users",
        json={
            "name": "Rahul",
            "email": "invalid-email",
        },
    )

    assert response.status_code == 422


def test_create_user_with_duplicate_email(client):
    payload = {
        "name": "Rahul",
        "email": "rahul@example.com",
    }

    first_response = client.post("/users", json=payload)
    second_response = client.post("/users", json=payload)

    assert first_response.status_code == 201
    assert second_response.status_code == 409
    assert second_response.json()["detail"] == (
        "Email already registered"
    )

What is happening here?

The fixture creates a fresh UserService for the tests and overrides the application's dependency:

app.dependency_overrides[get_user_service] = (
    lambda: test_service
)

This ensures that API requests use the test-specific service instead of the application's original shared instance.

The fixture then removes the dependency overrides after the test completes:

app.dependency_overrides.clear()

The context manager around TestClient also allows application startup and shutdown events to run.

In larger applications, prefer a dedicated application instance or carefully scoped overrides if tests run in parallel or share application configuration.

Why check status codes and response bodies?

A successful HTTP request doesn't necessarily mean the endpoint behaves correctly.

For example, a user creation endpoint might return HTTP 200 instead of the expected HTTP 201. It might also return unexpected fields or omit required data.

Testing both status codes and response content helps catch these problems.

7. Testing Request Validation

FastAPI uses Pydantic to validate incoming request data.

If a request violates the schema, FastAPI normally returns HTTP 422 with details about the validation error.

Let's add more validation tests:

def test_create_user_without_name(client):
    response = client.post(
        "/users",
        json={
            "email": "rahul@example.com",
        },
    )

    assert response.status_code == 422


def test_create_user_with_short_name(client):
    response = client.post(
        "/users",
        json={
            "name": "R",
            "email": "rahul@example.com",
        },
    )

    assert response.status_code == 422


def test_create_user_without_email(client):
    response = client.post(
        "/users",
        json={
            "name": "Rahul",
        },
    )

    assert response.status_code == 422

These tests verify that invalid requests are rejected before the business logic creates a user.

For production applications, validation tests should cover boundary conditions, missing fields, invalid data types, unexpected values, and any custom validation rules.

Avoid asserting every detail of FastAPI's validation response unless those details are part of your application's contract. Exact error messages can change when schemas or framework versions change.

8. Understanding Mocking in Pytest

Mocking replaces a real dependency with a controlled substitute.

Suppose your application sends a welcome email whenever a user registers. You don't want every test to send an actual email.

You can mock the email service and verify that it was called with the correct arguments.

Consider the following service:

# app/email_service.py

def send_welcome_email(email: str):
    # A real implementation could call an email provider.
    print(f"Sending welcome email to {email}")

Now imagine that your application imports this function into a module:

# app/registration.py

from app.email_service import send_welcome_email


def register_user(email: str):
    send_welcome_email(email)

    return {
        "email": email,
        "registered": True,
    }

Create a test:

# tests/test_registration.py

from unittest.mock import patch

from app.registration import register_user


def test_register_user_sends_email():
    with patch(
        "app.registration.send_welcome_email"
    ) as mock_email:
        result = register_user("user@example.com")

    assert result["registered"] is True

    mock_email.assert_called_once_with(
        "user@example.com"
    )

Here, patch() temporarily replaces the imported function with a mock.

The test verifies that registration calls the email function with the correct address without sending an actual email.

The most important mocking rule

Patch the object where your code looks it up, not necessarily where it was originally defined.

In this example, register_user() looks up send_welcome_email inside app.registration, so that's the correct target to patch.

Mocking is useful for email services, payment providers, external HTTP APIs, cloud services, and other dependencies that would make tests slow, expensive, or unreliable.

However, don't mock everything. Excessive mocking can make tests pass even when the real components don't work together.

9. Overriding FastAPI Dependencies

FastAPI dependency injection makes it easy to substitute services, databases, and authentication providers during testing.

For example, imagine an endpoint that depends on a database session:

from fastapi import Depends, FastAPI

app = FastAPI()


def get_db():
    # A real application would yield a database session.
    ...


@app.get("/health")
def health_check(db=Depends(get_db)):
    return {"status": "ok"}

A test can override the dependency:

from fastapi.testclient import TestClient

from app.main import app, get_db


def test_health_check():
    app.dependency_overrides[get_db] = (
        lambda: object()
    )

    try:
        with TestClient(app) as client:
            response = client.get("/health")

        assert response.status_code == 200
        assert response.json() == {"status": "ok"}

    finally:
        app.dependency_overrides.clear()

This example demonstrates the override mechanism, although the health endpoint doesn't actually use the database dependency.

In a real database-backed endpoint, you would provide a test database session or another suitable test double.

Testing with a separate database

For database integration tests, avoid connecting to production data. A safer setup uses a dedicated test database and resets its state between tests.

A typical workflow is:

  1. Configure a separate test database.

  2. Create the required tables or apply migrations.

  3. Provide a test database session through a dependency override.

  4. Execute API requests against the application.

  5. Roll back transactions or clean up test data.

  6. Close sessions and release connections.

For SQLAlchemy applications, transaction rollbacks can be useful, but their setup depends on your database, session configuration, and whether the code under test commits transactions.

For reliable tests, ensure that database constraints, transactions, and concurrency behavior match the production environment closely enough for the scenarios being tested.

10. Testing Asynchronous FastAPI Endpoints

FastAPI supports asynchronous endpoints using async def.

For example:

from fastapi import FastAPI

app = FastAPI()


@app.get("/async-data")
async def get_async_data():
    return {
        "message": "Async request completed"
    }

For simple API tests, FastAPI's regular TestClient can call asynchronous endpoints without requiring you to write an asynchronous test function.

However, if you need to test asynchronous functions directly, manage asynchronous resources, or interact with an async database client, use an asynchronous testing approach.

Install the required dependencies:

pip install pytest httpx anyio

Then write an asynchronous test:

import pytest
from httpx import ASGITransport, AsyncClient

from app.main import app


@pytest.mark.anyio
async def test_async_endpoint():
    transport = ASGITransport(app=app)

    async with AsyncClient(
        transport=transport,
        base_url="http://test",
    ) as client:
        response = await client.get("/async-data")

    assert response.status_code == 200

    assert response.json() == {
        "message": "Async request completed"
    }

ASGITransport allows HTTPX to send requests directly to the ASGI application.

This approach is useful when your tests already run inside an asynchronous event loop.

What about startup and shutdown?

Unlike the TestClient context manager, ASGITransport does not automatically manage the application's lifespan.

If your application initializes database connections, caches, or other resources during startup, configure lifespan management explicitly in your test setup. A library such as asgi-lifespan can help with this.

This distinction matters when a test passes locally but fails in an environment where required application resources have not been initialized.

11. Testing External HTTP APIs with Mocks

Suppose your FastAPI application retrieves weather information from an external service.

Calling the real service in every test can introduce network failures, rate limits, slow execution, and unpredictable results.

Instead, use HTTPX's mocking tools to simulate the external response.

Install RESPX:

pip install respx

Consider this service:

# app/weather_service.py

import httpx


async def fetch_weather(city: str):
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://weather.example.com/current",
            params={"city": city},
            timeout=5.0,
        )

        response.raise_for_status()

        return response.json()

Now test it without making a real network request:

# tests/test_weather_service.py

import httpx
import pytest
import respx

from app.weather_service import fetch_weather


@pytest.mark.anyio
@respx.mock
async def test_fetch_weather():
    route = respx.get(
        "https://weather.example.com/current"
    ).mock(
        return_value=httpx.Response(
            200,
            json={
                "city": "Jaipur",
                "temperature": 32,
            },
        )
    )

    result = await fetch_weather("Jaipur")

    assert result["city"] == "Jaipur"
    assert result["temperature"] == 32
    assert route.called

This test intercepts the outgoing HTTP request and returns a predefined response.

You can also simulate failures:

@pytest.mark.anyio
@respx.mock
async def test_fetch_weather_api_failure():
    respx.get(
        "https://weather.example.com/current"
    ).mock(
        return_value=httpx.Response(
            503,
            json={"detail": "Service unavailable"},
        )
    )

    with pytest.raises(httpx.HTTPStatusError):
        await fetch_weather("Jaipur")

The second test confirms that the service propagates an HTTP error when the external provider returns a server error.

In a production application, the calling layer should decide how to handle such failures. Depending on the business requirements, it might retry the request, return a controlled API error, or use cached data.

12. Testing Authentication and Authorization

Authentication tests are particularly important for APIs that expose private user data.

For example, an endpoint might require a bearer token before allowing access.

A robust test suite should verify:

  • Requests without credentials are rejected.

  • Invalid or expired tokens are rejected.

  • Valid tokens grant access.

  • Users cannot access resources they aren't authorized to view.

  • Administrative endpoints enforce role requirements.

If your application uses FastAPI's dependency injection for authentication, you can override the authentication dependency to test downstream behavior.

However, dependency overrides alone do not verify your real token validation logic. Keep separate tests for token generation, signature verification, expiration, and permission checks.

For security-sensitive code, include negative tests as well as successful requests. A test suite that checks only whether authorized users can access an endpoint may miss serious authorization vulnerabilities.

13. Measuring Test Coverage

Passing tests don't automatically mean that all important code paths have been tested.

Coverage tools help identify which parts of your code execute during your tests.

Install the Pytest coverage plugin:

pip install pytest-cov

Run your test suite with coverage:

pytest --cov=app --cov-report=term-missing

To generate an HTML report:

pytest --cov=app --cov-report=html

Pytest creates an HTML report inside the htmlcov/ directory.

The report helps identify untested lines and modules.

For example, you might discover that your duplicate-email error handler is never executed during testing. You can then add a test that covers that scenario.

Is 100% coverage necessary?

Not always.

High coverage can be useful, but it doesn't guarantee that tests check the correct behavior. A test might execute a line of code without verifying its output or handling its failure conditions.

Prioritize testing important business rules, security boundaries, error handling, and high-risk workflows rather than chasing a coverage percentage alone.

14. Common FastAPI Testing Mistakes

Mistake 1: Sharing application state between tests

If every test uses the same in-memory service, one test can affect another.

Solution: Create isolated fixtures and clean up shared state after each test.

Mistake 2: Forgetting to restore dependency overrides

Dependency overrides remain on the application until they are removed.

Solution: Use fixtures with try/finally cleanup or another reliable teardown mechanism.

Mistake 3: Testing only successful requests

Real applications receive invalid input, duplicate records, unauthorized requests, and unexpected external responses.

Solution: Include negative tests and boundary cases.

Mistake 4: Mocking the entire application

If all dependencies are mocked, tests may not detect integration problems between your real components.

Solution: Combine focused unit tests with integration tests that exercise real application components.

Mistake 5: Using production databases during testing

Test code can accidentally modify or delete real data.

Solution: Use a dedicated test database and explicit environment configuration.

Mistake 6: Ignoring application lifespan

Database pools, caches, and other resources may require initialization before requests are handled.

Solution: Use the appropriate test client or lifespan-management setup.

Mistake 7: Overusing exact error-message assertions

Framework-generated validation messages may change when dependencies are upgraded.

Solution: Assert stable API behavior and only check exact error messages when they are part of the application's public contract.

15. Running Tests in a CI/CD Pipeline

Automated tests become even more useful when they run whenever code changes.

For example, you can configure GitHub Actions to install dependencies and run Pytest for every push and pull request.

Create .github/workflows/tests.yml:

name: FastAPI Tests

on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install fastapi uvicorn pytest httpx anyio email-validator

      - name: Run tests
        run: pytest -v

This workflow runs the test suite automatically whenever a push or pull request triggers it.

For a real project, pin dependency versions and preferably install from a committed lockfile or a controlled requirements file. If your tests require PostgreSQL, Redis, or another external service, configure the required test dependencies in the CI environment as well.

You can also add coverage reporting and configure the pipeline to fail if coverage drops below an agreed threshold.

Conclusion

Testing FastAPI applications with Pytest helps you build reliable APIs and catch problems before deployment.

Start with unit tests for business logic, then add API tests using TestClient. Use dependency overrides to isolate services, mocks to simulate external integrations, and asynchronous testing tools when working with async resources.

As your project grows, add database integration tests, authentication checks, coverage reporting, and automated CI/CD execution.

The most effective test suite isn't necessarily the largest one. It's the one that consistently verifies the behavior your application depends on, catches regressions early, and gives you confidence when shipping changes.

Further Reading

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘