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 coffeeWas this page helpful?
Let us know how we did
