Skip to content

Writing Your First Test Case

The AAA pattern

A clean test follows Arrange β†’ Act β†’ Assert:

  1. Arrange: set up inputs
  2. Act: call the code under test
  3. Assert: verify output/side effects

Example: function + test

calculator.py
def divide(a: float, b: float) -> float:
    return a / b
calculator.py
def divide(a: float, b: float) -> float:
    return a / b
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_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_half
  • test_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 coffee

Was this page helpful?

Let us know how we did