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.
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
.
Write a unit test for a function that subtracts two numbers. Ensure that it passes all cases, including negative numbers and zero.
Answers: The unittest
module is used for unit testing. You can run tests using python -m unittest
.