Skip to main content
In this lesson you’ll learn how to create unit tests for a small FastAPI service and how tools like GitHub Copilot can speed up the process. We’ll start from a fragmented, hard-to-test example and refactor it into a compact, testable app/main.py. Then we’ll add pytest-based unit tests that mock database access so tests remain fast and deterministic.
A presentation slide titled "Creating Unit Tests" with a dark blue curved shape on the right containing the word "Demo." The slide also shows a small "© Copyright KodeKloud" note in the bottom-left.
Why this approach matters
  • Small modules with clear, testable boundaries make unit testing straightforward.
  • Isolating I/O (like the database) behind functions or context managers enables easy mocking.
  • Fast unit tests improve developer feedback loops and catch regressions early.
Initial (fragmented) example
  • The original code was split across many files and included duplicated logic. Below is a representative fragment showing an endpoint that relies on external modules. This fragmentation makes end-to-end tests slow and unit tests brittle.
Refactor: single-file, testable application
  • Consolidate the core application and database access into a small, well-documented module. This makes it clear where to patch/mocks during tests.
Main application (refactored app/main.py):
Run the app locally
  • Start with uvicorn and test an endpoint:
Sample uvicorn output:
Unit tests should not hit production or persistent databases. Mock database connections or use a temporary test database to keep unit tests fast and deterministic.
Generating tests with GitHub Copilot
  • GitHub Copilot can scaffold tests quickly if you add a focused comment like # generate unit tests near your functions or use a Copilot workspace flow. Always review and refine the generated tests to ensure they mock external dependencies and verify behavior (not just happy paths).
Choosing a test framework
  • pytest is used in this example because of its concise fixtures and compatibility with unittest-style tests.
  • Use fastapi.testclient.TestClient for synchronous tests against the FastAPI app.
Example pytest test file (app/test_main.py)
  • These unit tests patch the database access layer (get_db_connection or fetch_fake_data) so no real SQLite file is touched.
Why these tests work
  • Tests patch app.main.fetch_fake_data or app.main.get_db_connection so they do not access an actual SQLite database.
  • fastapi.testclient.TestClient allows synchronous testing of async endpoints.
  • unittest.mock.patch and MagicMock simulate connections, cursors, and database errors.
Running tests with pytest
  • Install pytest:
  • Run tests:
Example pytest output:
Validating tests catch regressions
  • Intentionally introduce a small bug (for example: count = request.count + 1) and rerun tests. A failure indicates your tests detect the regression and are valuable.
Testing strategy comparison Note: when showing examples with object literals or placeholders, keep them wrapped in backticks to avoid MDX parsing issues (for example: {"first_name": "John"} or <NODEPORT>). Alternative: unittest-based tests
  • If you prefer the standard library, write tests with unittest.TestCase. pytest discovers and runs unittest-style tests too. For database integration tests, use a temporary or in-memory database (do not point tests to production DB).
Do not run unit tests that modify or connect to production databases. Always isolate unit tests from persistent environments and use mocks or test-specific databases.
Summary and best practices
  • Refactor code into a small, testable module with clear I/O boundaries (database access isolated).
  • Use pytest + TestClient for fast API endpoint tests.
  • Mock database access (get_db_connection or fetch_fake_data) so unit tests remain isolated and deterministic.
  • Use GitHub Copilot to scaffold tests, but review, refine, and add edge-case assertions.
  • Keep tests focused: fast, small, and meaningful.
Links and references This completes the lesson on creating unit tests for a small FastAPI service.

Watch Video