0
0
PyTesttesting~15 mins

Arrange-Act-Assert pattern in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test addition function using Arrange-Act-Assert pattern
Preconditions (2)
Step 1: Arrange: Prepare two numbers, for example 3 and 5
Step 2: Act: Call the addition function with these two numbers
Step 3: Assert: Verify the result is 8
✅ Expected Result: The test passes confirming the addition function returns the correct sum
Automation Requirements - pytest
Assertions Needed:
Assert that the returned sum equals the expected value
Best Practices:
Use clear Arrange, Act, Assert comments or sections
Keep test functions small and focused
Use descriptive test function names
Automated Solution
PyTest
import pytest

# Function to add two numbers
def add_numbers(a: int, b: int) -> int:
    return a + b

# Test function following Arrange-Act-Assert pattern
def test_add_numbers():
    # Arrange
    num1 = 3
    num2 = 5
    expected_sum = 8

    # Act
    result = add_numbers(num1, num2)

    # Assert
    assert result == expected_sum, f"Expected {expected_sum} but got {result}"

This test script uses pytest to test a simple addition function.

Arrange: We set up the input numbers and the expected result.

Act: We call the function with the inputs.

Assert: We check if the function's output matches the expected sum.

Using comments clearly separates these steps, making the test easy to read and understand.

Common Mistakes - 3 Pitfalls
Not separating Arrange, Act, Assert steps clearly
Using hardcoded values inside assertions without variables
Not providing assertion messages
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers

Show Hint