Unit Testing in Python with Unittest
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 268 wordsLearn how to write and run unit tests in Python using the `unittest` module, including test cases, test suites, and mocking.
Unit testing ensures your code works as expected. This guide covers writing and running unit tests in Python using the unittest
module, including test cases, test suites, and mocking.
import unittest
def add(x, y):
return x + y
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Test cases can include multiple tests.
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
def test_subtract(self):
self.assertEqual(add(10, -3), 7)
if __name__ == "__main__":
unittest.main()
def suite():
suite = unittest.TestSuite()
suite.addTest(TestMathFunctions("test_add"))
suite.addTest(TestMathFunctions("test_subtract"))
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(suite())
Test suites allow you to group tests logically.
def suite():
suite = unittest.TestSuite()
suite.addTests(
unittest.defaultTestLoader.loadTestsFromTestCase(TestMathFunctions)
)
return suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(suite())
from unittest.mock import MagicMock
class TestAPI(unittest.TestCase):
def test_api_call(self):
mock_api = MagicMock(return_value={"status": "success"})
response = mock_api()
self.assertEqual(response["status"], "success")
if __name__ == "__main__":
unittest.main()
Mocking can simulate complex dependencies.
class TestService(unittest.TestCase):
def test_service(self):
mock_api = MagicMock()
mock_api.get_data.return_value = {"key": "value"}
service = MyService(mock_api)
data = service.fetch_data()
self.assertEqual(data["key"], "value")
if __name__ == "__main__":
unittest.main()
Run your tests from the command line.
python -m unittest test_module.py
Discover and run tests in the current directory.
python -m unittest discover
Test discovery with custom settings.
python -m unittest discover -s tests -p "test_*.py"
Unit testing with unittest
ensures your code works correctly and prevents future bugs. Practice writing test cases, creating test suites, and using mocking to test your Python code effectively.