Python unittest Module
Example
Create and run a simple unit test:
import unittest
class TestMath(unittest.TestCase):
def test_addition(self):
self.assertEqual(2 + 2, 4)
print('Addition test passed')
suite = unittest.TestLoader().loadTestsFromTestCase(TestMath)
runner = unittest.TextTestRunner(verbosity=0)
result = runner.run(suite)
print(f'Tests run: {result.testsRun}')
Try it Yourself »
Definition and Usage
The unittest module provides a framework for writing and running unit tests in Python.
Use it to create automated tests, verify code correctness, and practice test-driven development.
Members
Member | Description |
---|---|
main() | Command-line entry point for running tests. |
mock | Submodule providing mock objects for testing. |
skip() | Decorator to skip a test unconditionally. |
skipIf() | Decorator to skip a test if condition is true. |
skipUnless() | Decorator to skip a test unless condition is true. |
TestCase | Base class for creating test cases. |
TestCase.assertEqual() | Check if two values are equal. |
TestCase.assertFalse() | Check that expression is false. |
TestCase.assertRaises() | Check that an exception is raised. |
TestCase.assertTrue() | Check that expression is true. |
TestLoader | Class for loading tests from modules and classes. |
TestResult | Class for holding test results. |
TestSuite | Collection of test cases and test suites. |
TextTestRunner | Test runner that displays results in text format. |