Skip to main content
In this guide, you’ll learn how to streamline unit testing in a FastAPI project using GitHub Copilot, Pytest, and Python’s built-in unittest. We’ll start by refactoring an existing FastAPI app that generates fake data, then build a robust test suite to ensure code quality and reliability.

Refactoring the FastAPI Application

Before refactor
(Logic duplicated across 30+ files with multiple endpoints and Pydantic models.)
After refactor
All core logic is consolidated into app/main.py, simplifying maintenance and improving testability:
Consolidating your endpoints and database logic makes it easier to write targeted unit tests and debug issues.
Test the refactored API manually:

Writing Tests with pytest

Follow these steps to create and execute Pytest tests for your FastAPI app:
  1. Setup
    Create a tests/ directory in your project root.
  2. Create Tests
    Add tests/test_main.py with fixtures and test cases:
  1. Install Dependencies & Run
You’ll see:

Adding a Basic unittest Example

If you prefer Python’s built-in testing library, create tests/test_db_connectivity.py:
Run all unittest cases with:
In-memory SQLite databases (":memory:") are destroyed when the connection closes. Use file-based DBs for persistence.

Watch Video