Writing Your First Test Case
The AAA pattern
A clean test follows Arrange β Act β Assert:
- Arrange: set up inputs
- Act: call the code under test
- Assert: verify output/side effects
Example: function + test
calculator.py
def divide(a: float, b: float) -> float:
return a / bcalculator.py
def divide(a: float, b: float) -> float:
return a / btest_calculator.py
import unittest
from calculator import divide
class TestCalculator(unittest.TestCase):
def test_divide_returns_quotient(self):
# Arrange
a, b = 10, 2
# Act
result = divide(a, b)
# Assert
self.assertEqual(result, 5)
if __name__ == "__main__":
unittest.main()test_calculator.py
import unittest
from calculator import divide
class TestCalculator(unittest.TestCase):
def test_divide_returns_quotient(self):
# Arrange
a, b = 10, 2
# Act
result = divide(a, b)
# Assert
self.assertEqual(result, 5)
if __name__ == "__main__":
unittest.main()Test naming tips
Good test names describe behavior:
test_divide_by_two_returns_halftest_divide_by_two_returns_halftest_divide_by_zero_raisestest_divide_by_zero_raises
Avoid vague names like test1test1.
π§ͺ 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
