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

Python Testing with unittest

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)

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

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)

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):
            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):
        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__":
    unittest.main(argv=[""], exit=False)

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.