Intern
202
What is a unit test?
Answer from AI
sobes.tech AI
Unit testing is a testing method where the smallest testable component of an application (unit) is isolated and checked for correctness. In Python, a unit can be a function, a class method, a separate class, or a module. The goal is to ensure that each piece of code behaves as intended.
Advantages:
- Early error detection: Allows identifying problems at early stages of development.
- Simplifies debugging: Points to a specific non-working unit.
- Refactoring: Provides confidence that changes in the code do not break existing functionality.
- Documentation: Tests can serve as examples of how to use the code.
Main frameworks for unit testing in Python:
unittest: The standard module included in Python's standard library.pytest: A popular third-party framework with simpler syntax and extended capabilities.
Example of using unittest:
# my_module.py
def multiply(a, b):
return a * b
import unittest
from my_module import multiply
class TestMultiplyFunction(unittest.TestCase):
def test_positive_numbers(self):
# Test multiplication of positive numbers
self.assertEqual(multiply(2, 3), 6)
def test_zero_multiply(self):
# Test multiplication by zero
self.assertEqual(multiply(5, 0), 0)
def test_negative_numbers(self):
# Test multiplication of negative numbers
self.assertEqual(multiply(-2, -3), 6)
if __name__ == '__main__':
unittest.main()