0
0
Testing Fundamentalstesting~15 mins

Unit testing in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Unit test for a simple calculator add function
Preconditions (1)
Step 1: Call add(2, 3)
Step 2: Call add(-1, 5)
Step 3: Call add(0, 0)
✅ Expected Result: The add function returns 5, 4, and 0 respectively for the calls
Automation Requirements - unittest
Assertions Needed:
assertEqual for checking returned sum
Best Practices:
Use setUp method if needed for initialization
Test one behavior per test method
Name test methods clearly
Keep tests independent
Automated Solution
Testing Fundamentals
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.

Common Mistakes - 4 Pitfalls
Not using assertEqual and instead printing results
Testing multiple behaviors in one test method
{'mistake': "Not naming test methods starting with 'test_'", 'why_bad': 'unittest framework will not recognize methods as tests without this prefix.', 'correct_approach': "Always start test method names with 'test_'."}
Relying on external state or previous tests
Bonus Challenge

Now add data-driven testing with 3 different input pairs for the add function

Show Hint