Implementing Tests with unittest
Writing Test Cases
In the unittest framework, test cases are defined as subclasses of the unittest.TestCase class. Each test case method should start with the prefix test_ to be recognized as a test case.
import unittest
class TestMyFunction(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-2, -3), -5)
def test_add_zero(self):
self.assertEqual(add(0, 0), 0)
Assertion Methods
The unittest.TestCase class provides a variety of assertion methods to help you verify the expected behavior of your code. Some commonly used assertion methods include:
| Method |
Description |
assertEqual(a, b) |
Checks if a == b |
assertNotEqual(a, b) |
Checks if a != b |
assertTrue(x) |
Checks if x is True |
assertFalse(x) |
Checks if x is False |
assertIn(a, b) |
Checks if a is in b |
assertIsNone(x) |
Checks if x is None |
Organizing Test Suites
You can group related test cases into test suites using the unittest.TestSuite class. This allows you to run multiple test cases together.
import unittest
## Define test cases
class TestMyModule(unittest.TestCase):
def test_function1(self):
## Test function1
pass
def test_function2(self):
## Test function2
pass
## Create a test suite
suite = unittest.TestSuite()
suite.addTest(TestMyModule('test_function1'))
suite.addTest(TestMyModule('test_function2'))
## Run the test suite
runner = unittest.TextTestRunner()
runner.run(suite)
Mocking and Patching
In some cases, your unit tests may depend on external resources or components that are difficult to control or simulate. The unittest.mock module provides tools to create mocks and patches to replace these dependencies, allowing you to isolate your tests.
from unittest.mock import patch
@patch('my_module.external_function')
def test_my_function(mock_external_function):
mock_external_function.return_value = 42
result = my_function()
self.assertEqual(result, 42)
By using mocks and patches, you can ensure that your unit tests focus on the specific behavior of the code under test, without being affected by external dependencies.