Definition
The process of verifying that an individual “unit” of code—typically a single function or method—behaves exactly as expected in a variety of situations. In Python, this is primarily managed using the unittest standard library module.
Why It Matters
Unit testing is the ‘firewall’ against software bugs. By verifying each small piece of code in isolation, a developer can build complex systems with confidence, knowing that a change in one part won’t silently break everything else.
Core Concepts
- Test Case: A collection of unit tests that check a specific function or class.
- Assertions: Methods (like
assertEqual,assertTrue,assertIn) that compare an actual result with an expected outcome. - The
setUp()Method: A special method inunittest.TestCasethat runs before every test method, used to initialize objects or data once for the entire test case. - Test-Driven Refactoring: If a test fails, you modify the source code to pass the test, ensuring the behavior remains consistent even if the implementation changes.
import unittest
def add(a, b):
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()