Unit test for a simple calculator add function
Preconditions (1)
✅ Expected Result: The add function returns 5, 4, and 0 respectively for the calls
import unittest # Simple calculator module class Calculator: @staticmethod def add(a, b): return a + b class TestCalculator(unittest.TestCase): def test_add_positive_numbers(self): result = Calculator.add(2, 3) self.assertEqual(result, 5) def test_add_negative_and_positive(self): result = Calculator.add(-1, 5) self.assertEqual(result, 4) def test_add_zeros(self): result = Calculator.add(0, 0) self.assertEqual(result, 0) if __name__ == '__main__': unittest.main()
This code defines a simple Calculator class with a static add method.
The TestCalculator class inherits from unittest.TestCase and contains three test methods.
Each test calls the add method with specific inputs and uses assertEqual to check the output matches the expected sum.
Tests are independent and clearly named to show what they check.
Running this script will execute all tests and report pass/fail results.
Now add data-driven testing with 3 different input pairs for the add function
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