Coding

Unit Test vs Integration Test: Differences with Python Examples

A unit test checks one small piece of code, such as a function or class, in isolation and runs in milliseconds. An integration test checks that several pieces work together, such as your code and a real database, and catches the bugs that live in the connections between them.

Unit test vs integration test at a glance

Unit testIntegration test
ScopeOne function, class or small group of classesTwo or more components working together
DependenciesReplaced with test doubles, or simple real objectsReal (a real database, file system, queue) or a faithful stand-in
SpeedMillisecondsSlower: setup, I/O, sometimes network
When it failsPoints at the exact functionTells you something in the chain is wrong
CatchesLogic errors, edge cases, wrong calculationsWrong SQL, wrong config, schema mismatches, broken contracts between modules
Typical countManyFewer

Neither term has a precise official definition. Martin Fowler calls unit testing "very ill-defined": what counts as a unit varies by team. The useful distinction is practical: does the test exercise one piece of logic alone, or the joins between pieces?

A runnable example: one module, both kinds of test

Here is a small Python module with a pure function and a class that talks to SQLite:

# orders.py
import sqlite3

def order_total(items, discount_pct=0):
    """Sum quantity * unit price, then apply a percentage discount."""
    subtotal = sum(qty * price for qty, price in items)
    return round(subtotal * (100 - discount_pct) / 100, 2)

class OrderRepo:
    def __init__(self, conn):
        self.conn = conn
        conn.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total REAL)")

    def save(self, total):
        cur = self.conn.execute("INSERT INTO orders (total) VALUES (?)", (total,))
        self.conn.commit()
        return cur.lastrowid

    def get(self, order_id):
        row = self.conn.execute("SELECT total FROM orders WHERE id = ?", (order_id,)).fetchone()
        return row[0] if row else None

Unit tests for the pure function need nothing but the function:

# test_unit.py
import unittest
from orders import order_total

class OrderTotalTest(unittest.TestCase):
    def test_sums_lines(self):
        self.assertEqual(order_total([(2, 9.99), (1, 5.00)]), 24.98)

    def test_applies_discount(self):
        self.assertEqual(order_total([(1, 100.00)], discount_pct=15), 85.00)

    def test_empty_order_is_zero(self):
        self.assertEqual(order_total([]), 0)

Integration tests for the repository use a real SQLite database in a temporary folder:

# test_integration.py
import os, sqlite3, tempfile, unittest
from orders import OrderRepo, order_total

class OrderRepoIntegrationTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.conn = sqlite3.connect(os.path.join(self.tmp.name, "shop.db"))

    def tearDown(self):
        self.conn.close()
        self.tmp.cleanup()

    def test_saved_total_reads_back(self):
        repo = OrderRepo(self.conn)
        order_id = repo.save(order_total([(2, 9.99), (1, 5.00)]))
        self.assertEqual(repo.get(order_id), 24.98)

    def test_missing_order_returns_none(self):
        self.assertIsNone(OrderRepo(self.conn).get(999))

Real output from Python 3.12.2 with SQLite 3.43.1 on Windows 11:

> python -m unittest -v test_unit.py
test_applies_discount (test_unit.OrderTotalTest.test_applies_discount) ... ok
test_empty_order_is_zero (test_unit.OrderTotalTest.test_empty_order_is_zero) ... ok
test_sums_lines (test_unit.OrderTotalTest.test_sums_lines) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

> python -m unittest -v test_integration.py
test_missing_order_returns_none (test_integration.OrderRepoIntegrationTest.test_missing_order_returns_none) ... ok
test_saved_total_reads_back (test_integration.OrderRepoIntegrationTest.test_saved_total_reads_back) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.024s

OK

The three unit tests finished in under a millisecond (unittest reports 0.000s). The two integration tests took 24 ms, because each creates a database file on disk. That's still fast, but the ratio is typical: multiply by a few thousand tests and a slow external service, and the difference decides how often people run the suite.

A bug only the integration test catches

Now introduce a realistic mistake: the SQL in get() uses a column name that doesn't exist.

row = self.conn.execute("SELECT total FROM orders WHERE order_id = ?", (order_id,)).fetchone()

The unit tests still pass, because they never touch the database. Running the full suite (excerpt of the output, path shortened):

  File "C:\work\orders.py", line 19, in get
    row = self.conn.execute("SELECT total FROM orders WHERE order_id = ?", (order_id,)).fetchone()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: no such column: order_id

----------------------------------------------------------------------
Ran 5 tests in 0.050s

FAILED (errors=2)

If OrderRepo had been tested with a mocked connection, that test would have passed too: a mock accepts whatever SQL string you hand it. This is the core argument for integration tests. Code whose whole job is talking to something else can only be verified by letting it talk to that thing, or to a faithful copy of it.

The reverse case matters just as much. If order_total rounded wrongly for a 15% discount, the integration test might never notice, because it only checks one specific order. The unit tests target that logic directly, including edge cases like an empty order, and point straight at the function when they fail.

Mocks and test doubles: where the line blurs

Python's unittest.mock lets you replace parts of the system under test with mock objects and then make assertions about how they were used. Replacing a collaborator this way keeps a test fast and focused. Fowler distinguishes two styles of unit test:

  • Solitary: collaborators are replaced with doubles, so a bug in another class can't make this test fail.
  • Sociable: real collaborators are used, as long as the test stays fast. Fowler says he mostly works this way, using doubles only for awkward collaborators such as remote services.

When you patch, the unittest.mock documentation's main rule is to patch where an object is looked up, not where it's defined. If b.py does from a import SomeClass, you patch b.SomeClass. Getting that wrong is a common reason a mock seems to have no effect.

Fowler also splits integration tests into two kinds. Narrow integration tests exercise only the code that talks to another service, often against a test double of that service, and can be nearly as fast as unit tests. Broad integration tests need live versions of every service; he prefers to call those system or end-to-end tests. When a double stands in for a real service, contract tests check that the double still behaves like the real thing.

How many of each?

There's no correct ratio, but the trade-offs point one way:

  • Lots of unit tests for logic: calculations, parsing, validation, branching rules, edge cases. They're cheap to write, run in milliseconds, and pinpoint failures.
  • Integration tests at every boundary: each database query layer, file format reader and writer, HTTP client, message queue consumer. One or two per path is often enough, since the logic behind them is already unit-tested.
  • A few end-to-end tests for the critical user journeys, such as sign-up and checkout.

Speed sets the budget. Fowler describes a small suite he runs constantly while coding, which should take a few seconds at most, and a fuller commit suite run several times a day. He cites Kent Beck's rule of thumb that the commit suite should take no more than ten minutes.

Making integration tests reliable

  • Isolate state. Give each test its own temporary database or folder, as the example does with tempfile.TemporaryDirectory(), and clean up in tearDown. Tests that share a database fail in confusing ways depending on run order.
  • Use the same engine as production where it matters. SQLite is great for examples, but if production runs PostgreSQL, SQL dialect differences can hide bugs. Run the real engine in a container for those tests.
  • Don't call third-party APIs live in every run. Use a narrow integration test against a stand-in, plus contract tests, so a vendor's outage doesn't break your build.
  • Never use real credentials or customer data in tests. Generate fixtures instead; the larely test data generator produces fake names, emails and addresses as CSV or JSON.

When a test does fail, a debugger is often quicker than adding prints; see how to use breakpoints in VS Code.

Frequently asked questions

Should I write unit tests or integration tests first?
Write whichever gives the fastest useful feedback for the code you're changing. Pure logic, such as calculations, parsing and validation, is easiest to pin down with unit tests. Code whose job is talking to a database, file system or another service needs an integration test, because a unit test with that dependency mocked out would not test the part most likely to break.
Is a test that uses a mock a unit test?
Usually, yes. Replacing collaborators with test doubles such as mocks isolates the code under test, which Martin Fowler calls a solitary unit test. Tests that use the real collaborators can still be unit tests if they stay small and fast; he calls those sociable unit tests.
What is the difference between an integration test and an end-to-end test?
An integration test checks that a few components work together, such as your repository class and a real database. An end-to-end test drives the whole system the way a user would, through the UI or public API with every service running. Fowler suggests calling those broad tests system or end-to-end tests and reserving 'narrow integration test' for the focused kind.
How fast should a test suite be?
Fast enough that you run it constantly. Martin Fowler describes a small suite run while coding that should take seconds at most, and cites Kent Beck's rule of thumb that the fuller suite run before committing should take no more than ten minutes.

Sources