Introduction
When building software, small parts can break without us noticing. Finding these problems early is hard if we only test the whole program. Unit testing helps by checking each small piece separately to catch errors quickly.
Imagine building a car by assembling many small parts. Before putting the whole car together, you test each part like the engine or brakes separately to make sure they work well. This way, you avoid big problems later when the car is complete.
┌───────────────┐
│ Software │
│ Program │
└──────┬────────┘
│
▼
┌───────────────┐
│ Unit Test │
│ (Small Part) │
└──────┬────────┘
│
▼
┌───────────────┐
│ Test Result │
│ (Pass / Fail) │
└───────────────┘import unittest def add(a, b): return a + b class TestAddFunction(unittest.TestCase): def test_add_positive(self): self.assertEqual(add(2, 3), 5) def test_add_negative(self): self.assertEqual(add(-1, -1), -2) def test_add_zero(self): self.assertEqual(add(0, 0), 0) if __name__ == '__main__': unittest.main()
unit testing in software development?assert?assert expression where expression must be True for test to pass.assert add(2, 3) == 5. assert add(2, 3) = 5 uses single = which is assignment, invalid here. assert(add(2, 3) = 5) uses single = which is assignment, invalid syntax. assert add(2, 3) equals 5 uses invalid keyword 'equals'.def multiply(a, b):
return a * b
assert multiply(3, 4) == 12
assert multiply(0, 5) == 0
assert multiply(-1, 3) == -3
assert multiply(2, 2) == 5def divide(a, b):
return a / b
assert divide(10, 2) == 5
assert divide(5, 0) == 0Pass the test and this pattern moves unknown