0
0
Testing Fundamentalstesting~15 mins

Test-driven development (TDD) concept in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Create a function to add two numbers using TDD
Preconditions (2)
Step 1: Write a test that calls the add function with inputs 2 and 3
Step 2: Assert that the result is 5
Step 3: Run the test and see it fail because the add function does not exist yet
Step 4: Create the add function that takes two numbers and returns their sum
Step 5: Run the test again and verify it passes
Step 6: Add another test case with inputs -1 and 1, expecting 0
Step 7: Run all tests and verify they pass
✅ Expected Result: Tests initially fail, then pass after implementing the add function correctly
Automation Requirements - pytest
Assertions Needed:
Assert that add(2, 3) returns 5
Assert that add(-1, 1) returns 0
Best Practices:
Write tests before writing the function code
Keep tests small and focused
Use clear and descriptive test names
Run tests frequently to check progress
Automated Solution
Testing Fundamentals
import pytest

# Step 1: Write failing tests first

def test_add_positive_numbers():
    assert add(2, 3) == 5

def test_add_negative_and_positive():
    assert add(-1, 1) == 0

# Step 2: Implement the function

def add(a, b):
    return a + b

# To run tests, use command: pytest <filename>.py

First, we write tests that call the add function with specific inputs and check the expected output. Since add does not exist yet, running tests will fail. Then, we create the add function that returns the sum of two numbers. Running tests again will pass, confirming the function works as expected. This follows the TDD cycle: write a failing test, write code to pass the test, refactor if needed.

Common Mistakes - 3 Pitfalls
Writing the function code before writing any tests
Writing large tests that check many things at once
Not running tests frequently during development
Bonus Challenge

Now add data-driven testing with 3 different input pairs and expected sums

Show Hint