Create a function to add two numbers using TDD
Preconditions (2)
✅ Expected Result: Tests initially fail, then pass after implementing the add function correctly
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.
Now add data-driven testing with 3 different input pairs and expected sums
Test-driven development (TDD)?1. Write a test that fails
2. Write code to pass the test
3. Refactor the code
4. Repeat for next feature
Pass the test and this pattern moves unknown