Browse Python Topics ▼
Pick a Web Framework

Python Unittest Framework

📂 Testing & Code Quality 📘 Lesson 50 of 57

Master Python's standard library testing framework. Write TestCase classes, assert methods, setUp/tearDown lifecycle hooks, and mock dependencies with unittest.mock.

While pytest is the most popular testing framework in the third-party ecosystem, there are many situations where you cannot install external packages:

  • Working in restricted, air-gapped enterprise environments.
  • Building standard library packages that must have zero third-party dependencies.
  • Writing lightweight automation scripts that must run instantly on any machine with Python installed.

For these scenarios, Python includes unittest (originally known as PyUnit, modeled after Java’s JUnit) directly in its standard library.

unittest requires zero installation, works out of the box on every computer in the world with Python, and provides a robust, object-oriented test runner.


1. Anatomy of a unittest Test Case

Unlike pytest which uses standalone functions, unittest organizes tests into classes inheriting from unittest.TestCase:

# test_math.py
import unittest

def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b

class TestMathOperations(unittest.TestCase):
    # Every test method MUST start with the prefix `test_`!
    def test_add_positive_numbers(self):
        result = add(10, 5)
        self.assertEqual(result, 15)

    def test_add_negative_numbers(self):
        result = add(-3, -7)
        self.assertEqual(result, -10)

    def test_divide_by_zero_raises_error(self):
        # Testing expected exceptions using a context manager:
        with self.assertRaises(ZeroDivisionError):
            divide(10, 0)

if __name__ == "__main__":
    unittest.main()

When you execute this script in your terminal (python test_math.py), unittest.main() discovers all methods starting with test_ and runs them:

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

Each dot (.) represents a passing test!


2. Common TestCase Assertion Methods

Rather than relying on plain assert, unittest.TestCase provides explicit assertion helper methods with rich failure reporting:

Assertion MethodCondition CheckedNotes
self.assertEqual(a, b)a == bVerifies value equality
self.assertNotEqual(a, b)a != bVerifies values differ
self.assertTrue(x)bool(x) is TrueVerifies truthiness
self.assertFalse(x)bool(x) is FalseVerifies falsiness
self.assertIs(a, b)a is bVerifies identical memory address
self.assertIsNone(x)x is NoneVerifies value is None
self.assertIn(item, list)item in listVerifies sequence membership
self.assertRaises(Error)Context managerVerifies expected exception

3. Test Lifecycle: setUp() and tearDown()

When testing complex components (like database models or user sessions), you need a fresh starting state for every individual test so tests cannot contaminate one another:

import unittest

class TestShoppingCart(unittest.TestCase):
    def setUp(self):
        """Runs BEFORE every single test method."""
        print("\n[Setup] Initializing empty shopping cart")
        self.cart = []

    def tearDown(self):
        """Runs AFTER every single test method."""
        print("[Teardown] Clearing cart resources")
        self.cart.clear()

    def test_add_item(self):
        self.cart.append("Laptop")
        self.assertEqual(len(self.cart), 1)

    def test_cart_initially_empty(self):
        # Thanks to setUp, self.cart is brand-new and unaffected by other tests!
        self.assertEqual(len(self.cart), 0)

if __name__ == "__main__":
    unittest.main()

4. The Secret Superpower: unittest.mock

How do you test a function that charges a customer’s real credit card or sends an SMS message across the internet? You don’t want your automated tests charging thousands of dollars or failing whenever your internet connection flickers!

Python includes unittest.mock, a powerful mocking library that lets you replace real functions with simulated dummy objects:

from unittest.mock import patch
import unittest

# Function that normally calls a remote external API:
def get_user_status(user_id):
    import requests
    response = requests.get(f"https://api.example.com/users/{user_id}")
    return response.json()["status"]

class TestAPIClient(unittest.TestCase):
    # Temporarily patch requests.get during this test:
    @patch("requests.get")
    def test_get_user_status(self, mock_get):
        # Configure the fake response:
        mock_get.return_value.json.return_value = {"status": "ACTIVE"}
        
        # Call our function:
        status = get_user_status(42)
        
        # Verify result without making any real network calls!
        self.assertEqual(status, "ACTIVE")
        mock_get.assert_called_once_with("https://api.example.com/users/42")

if __name__ == "__main__":
    unittest.main()

5. Running Tests from the Command Line

You don’t need if __name__ == "__main__": in every file. You can run automated discovery across your entire project from your terminal:

# Discover and run all test files matching `test*.py` in current directory:
python -m unittest

# Run with verbose output:
python -m unittest -v

# Run tests in a specific folder:
python -m unittest discover tests

Summary & What’s Next

  • unittest is built into Python’s standard library with zero external dependencies.
  • Organize tests in classes inheriting from unittest.TestCase.
  • Prefix all test methods with test_.
  • Use setUp() and tearDown() to guarantee test isolation.
  • Use unittest.mock to simulate external networks, APIs, and databases.

Automated tests check whether your code runs correctly. But how do you ensure your code is cleanly formatted, follows PEP 8 standards, and has no hidden bugs? Learn about automated linters and formatters in code-quality.

Test your understanding of Python Unittest Framework

Quick interactive practice questions with instant feedback.

Take Quiz →