Skip to content

Unit Testing - Testing Individual Components

What is a β€œunit”?

A unit is the smallest testable piece of your code.

Usually:

  • a function
  • a method
  • a small class

What unit tests should be

  • fast (no DB, no network)
  • deterministic (same input β†’ same output)
  • focused (one behavior per test)

What unit tests should avoid

  • real HTTP calls
  • real databases
  • time-dependent behavior (unless controlled)

Example unit logic

price.py
def apply_discount(price: float, percent: float) -> float:
    if percent < 0 or percent > 100:
        raise ValueError("percent must be between 0 and 100")
    return round(price * (1 - percent / 100), 2)
price.py
def apply_discount(price: float, percent: float) -> float:
    if percent < 0 or percent > 100:
        raise ValueError("percent must be between 0 and 100")
    return round(price * (1 - percent / 100), 2)

A unit test for this function is small and has no dependencies.

Key takeaway

Unit tests are your fastest safety net for refactoring.

πŸ§ͺ Try It Yourself

Exercise 1 – Write a unittest TestCase

Exercise 2 – assertRaises

Exercise 3 – setUp and tearDown

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did