Simple example using Python’s unittest module to demonstrate basic unit testing. In this example, we’ll create a simple function and write test cases to ensure its correctness.
Step 1: Create a Python Module
Create a file named math_operations.py with the following content:
# math_operations.py
def add_numbers(a, b):
return a + b
def multiply_numbers(a, b):
return a * b
Step 2: Write Unit Tests
Create another file named test_math_operations.py to write unit tests for the math_operations module:
# test_math_operations.py
import unittest
from math_operations import add_numbers, multiply_numbers
class TestMathOperations(unittest.TestCase):
def test_add_numbers(self):
result = add_numbers(3, 7)
self.assertEqual(result, 10)
def test_multiply_numbers(self):
result = multiply_numbers(3, 4)
self.assertEqual(result, 12)
if __name__ == '__main__':
unittest.main()
Step 3: Run the Tests
In the terminal or command prompt, navigate to the directory containing your Python files (math_operations.py and test_math_operations.py). Run the following command:
python -m unittest test_math_operations.py
This command will discover and run the tests in test_math_operations.py. If everything is correct, you should see an output indicating that all tests passed.
Example Output:
markdownCopy code..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
The unittest module executed two tests (test_add_numbers and test_multiply_numbers), and both passed successfully.
Feel free to modify the functions and test cases to explore more features of the unittest module. Unit testing is a crucial aspect of software development, helping ensure that individual components of your code work as expected.