Test addition function using Arrange-Act-Assert pattern
Preconditions (2)
✅ Expected Result: The test passes confirming the addition function returns the correct sum
Jump into concepts and practice - no test required
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.
Now add data-driven testing with 3 different pairs of numbers
def test_sum():
# Arrange
numbers = [1, 2, 3]
expected = 6
# Act
result = sum(numbers)
# Assert
assert result == expected
def test_uppercase():
# Arrange
text = "hello"
# Act
result = text.upper
# Assert
assert result == "HELLO"
divide(a, b) that returns the division of two numbers. Using Arrange-Act-Assert, which test correctly checks that dividing by zero raises a ZeroDivisionError?with pytest.raises(ZeroDivisionError): correctly checks for the exception during Act step.