Write Test Cases: Create a Python script for your test cases. Each test case is typically a subclass of unittest.TestCase
, and test methods are named starting with test_
. Within each test method, you'll use assertions (self.assertEqual()
, self.assertTrue()
, etc.) to verify the behavior of your code.
import unittest
from my_module import my_function
class TestMyFunction(unittest.TestCase):
def test_my_function(self):
result = my_function(2, 3)
self.assertEqual(result, 5)
Run Tests: You can run your tests using the unittest
test runner. You can either run the test script directly from the command line or use a test runner like unittest
's built-in test runner, or third-party runners like pytest
.
Command Line:
python -m unittest test_module.py
Using unittest
Test Runner:
if __name__ == '__main__':
unittest.main()
Setup and Teardown: unittest
supports setup and teardown methods (setUp()
and tearDown()
) that are called before and after each test method, respectively. These methods are useful for preparing the environment for tests or cleaning up after tests.
class TestMyFunction(unittest.TestCase):
def setUp(self):
# Initialize resources before each test
self.api = getApi()
pass
def tearDown(self):
# Clean up resources after each test
pass
def test_my_function(self):
# Test code
pass
Disable Tests: You can disable a test method by using the unittest.skip()
decorator.
@unittest.skip("Reason for skipping this test")
def test_disabled_method(self):
# Test code for disabled method
pass