Skip to content

Unit Testing

Unit tests check small units of code in isolation. They should be fast and deterministic.

Principles

  • Test one behavior per test.
  • Arrange, Act, Assert structure.
  • Use fixtures to set up and tear down repeated state.

Example (pytest)

# test_math.py
def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3

Run with:

pytest -q

Gotchas

  • Tests that depend on external services are brittle (use mocks).
  • Flaky tests (time-dependent, order-dependent) reduce confidence.