← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 3 of 15

Python Testing with unittest

unittest lets you write small checks that test whether your code gives the right answers, like a teacher marking your homework automatically. Running them again tells you if something broke.

Introduction to Unit Testing

Unit testing means writing code that automatically verifies individual pieces of your application -- functions or classes -- behave correctly, rather than manually re-checking behavior by hand every time you make a change.

unittest is Python's built-in testing framework, modeled after the xUnit family found in many other languages.

Example: Introduction to Unit Testing

python
import unittest

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

class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)  # verifies add() behaves correctly

unittest.main(argv=[""], exit=False)  # runs the tests without exiting the interpreter

Writing Assertions

Assertion methods like assertEqual(a, b) check that two values match and produce a clear, specific failure message naming both values if they don't -- more informative than a bare assert a == b, which only tells you the assertion failed without showing what the actual values were.

Example: Writing Assertions

python
import unittest

class TestMath(unittest.TestCase):
    def test_equal(self):
        self.assertEqual(2 + 2, 4)  # gives a clear failure message naming both values

unittest.main(argv=[""], exit=False)

Testing Exceptions

assertRaises() is used as a context manager to verify that a block of code raises a specific exception type when given invalid input, letting you test error-handling paths as rigorously as you test the normal success path.

Example: Testing Exceptions

python
import unittest

def divide(a, b):
    return a / b

class TestDivide(unittest.TestCase):
    def test_zero_division(self):
        with self.assertRaises(ZeroDivisionError):  # verifies this specific exception is raised
            divide(1, 0)

unittest.main(argv=[""], exit=False)

Setup and Teardown Methods

setUp() runs automatically before every individual test method in a test class, and tearDown() runs automatically after each one -- the standard place to prepare shared fixtures (like mock files or database connections) and then clean them up, without repeating that setup code in every single test.

Example: Setup and Teardown Methods

python
import unittest

class TestExample(unittest.TestCase):
    def setUp(self):  # runs automatically before every test method
        self.value = 10

    def test_value(self):
        self.assertEqual(self.value, 10)

unittest.main(argv=[""], exit=False)

Running unittest inside Script

Adding unittest.main() inside an if __name__ == __main__: guard lets you run all the tests in a file directly by executing that script, without needing to invoke a separate test-runner command -- convenient for quick, single-file test suites.

Example: Running unittest inside Script

python
import unittest

class TestBasic(unittest.TestCase):
    def test_true(self):
        self.assertTrue(1 == 1)

if __name__ == "__main__":  # lets this file run its tests directly
    unittest.main(argv=[""], exit=False)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Naming test methods without the test_ prefix, so unittest never runs them.
  2. Making tests depend on each other's order or shared state, so they pass or fail randomly.
  3. Using assertTrue(a == b) instead of assertEqual(a, b), which gives a much less helpful failure message.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.