How do you write a unit test using unittest in Python?
Writing Python unit tests with unittest: A guide
Follow these steps to write a unit test in Python using the unittest framework:
- Import the unittest module.
- Create a test case class that subclasses unittest.TestCase.
- Write test methods within the test case class to test the functions or methods you want to test.
- Use unittest assertion methods.TestCase (such as assertEqual(), assertTrue(), etc.) to check the expected outcomes.
- Optionally, use the setUp() method to set up any preconditions for the tests.
- Optionally, use the tearDown() method to clean up after each test.
The following is an example of writing a simple unit test for a Python function using unittest:
Let's suppose that we have a function called sum_numbers() that calculates the sum of two numbers.
Code:
# math_operations.py
def sum_numbers(a, b):
return a + b
Now, let's write a unit test for the sum_numbers() function using unittest:
Code:
import unittest
from math_operations import sum_numbers
class TestSumFunction(unittest.TestCase):
def test_positive_numbers(self):
result = sum_numbers(10, 20)
self.assertEqual(result, 30)
def test_negative_numbers(self):
result = sum_numbers(-10, -2)
self.assertEqual(result, -12)
def test_mixed_numbers(self):
result = sum_numbers(8, -14)
self.assertEqual(result, -6)
if __name__ == '__main__':
unittest.main()
Output:
Reloaded modules: math_operations ... ---------------------------------------------------------------------- Ran 3 tests in 0.002s OK
In the above example, we have created a test case class called TestSumFunction, which subclasses unittest.TestCase. We have written three test methods (test_positive_numbers(), test_negative_numbers(), and test_mixed_numbers()), each testing a different scenario for the sum_numbers() function.
Each test method calls the sum_numbers() function with specific arguments and uses the assertEqual() method from unittest. TestCase checks if the result matches the expected outcome.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/how-do-you-write-a-unit-test-using-unittest-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics