Labs ICT
โญ Pro Login

What is unittest?

Learn about Python's built-in unittest framework and its core concepts

What is unittest?

unittest is Python's built-in unit testing framework, inspired by JUnit from Java. It provides a rich set of tools for constructing and running tests, assertions, and test organization. No external installation is needed โ€” it comes bundled with the Python standard library.

Core Concepts

The unittest framework is built around four key pillars:

  • TestCase โ€” A class that contains individual test methods and assertions.
  • TestSuite โ€” A collection of test cases and suites that are run together.
  • TestRunner โ€” The component that executes tests and reports results.
  • TestResult โ€” An object that stores the result of running tests.

Your First Test

import unittest

class TestMath(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(1 + 1, 2)

    def test_subtraction(self):
        self.assertEqual(5 - 3, 2)

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

Why Use unittest?

  • Built-in โ€” no pip install required.
  • Rich assertion methods for comparing values, checking exceptions, and more.
  • Automatic test discovery based on naming conventions.
  • Support for setUp/tearDown fixtures for test isolation.
  • Mocking capabilities via unittest.mock.
  • Integrates well with CI/CD pipelines and coverage tools.

Key Takeaway

unittest is the standard way to write automated tests in Python. Everything you need is already in the standard library โ€” just import unittest and start writing tests.

๐Ÿงช Quick Quiz

What module provides the unittest framework in Python?