Python Unit Testing
Unit testing is essential for verifying that your code works correctly. In Python, you can use the built-in unittest module to write tests for your functions.
Writing Unit Tests
Here is an example of how to write and run a simple test using unittest:
import unittest
def add(a, b):
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(3, 4), 7)
self.assertEqual(add(-1, 1), 0)
if __name__ == "__main__":
unittest.main()
The test class TestMathOperations contains a test method test_add(), which checks if the add() function works correctly. You can run the tests with the command python -m unittest test_file.py.
Activity
Try It Yourself!
Write a unit test for a function that subtracts two numbers. Ensure that it passes all cases, including negative numbers and zero.
Quick Quiz
Quick Quiz
- What module do you use for unit testing in Python?
- How do you run unit tests in Python?
Answers: The unittest module is used for unit testing. You can run tests using python -m unittest.