Lesson 14 — Automation
Unit Testing Frameworks
Unit testing frameworks provide the structure and tools — test runners, assertions, and reporting — needed to write and execute fast, focused tests of individual code units.
Anatomy of a Unit Test
Most unit tests follow the same simple structure: arrange the necessary setup, act by calling the function being tested, and assert that the result matches what was expected.
Python — A PyTest unit test
def add(a, b):
return a + b
def test_add_two_positive_numbers():
# Arrange
a, b = 2, 3
# Act
result = add(a, b)
# Assert
assert result == 5
Common Mistakes
- Writing unit tests that depend on external systems (a real database or network call), blurring the line into integration testing and making tests slow and flaky.
- Testing multiple unrelated behaviours in a single test function, making failures harder to diagnose.
- Giving tests vague names like test1 instead of descriptive ones like test_add_rejects_negative_numbers.
- Not testing edge cases and error conditions, only the simplest expected input.
Professional Tip
Name unit tests descriptively enough that a failure message alone tells you roughly what went wrong, e.g. test_divide_by_zero_raises_exception rather than test3.
Your Turn
Write three unit tests for a function that calculates a shopping cart's total: one for an empty cart, one for a single item, and one for multiple items.
Mini Quiz
What do the three steps 'Arrange, Act, Assert' describe in unit testing?
"Arrange, Act, Assert" is a widely used pattern for structuring a single unit test clearly: set up the needed data, perform the action being tested, then verify the result.