Assertions

Introduction

Automation testing is not just about performing actions such as clicking buttons or entering text. It is equally important to verify that the application behaves as expected. This verification is performed using assertions.

An assertion compares the actual result produced by the application with the expected result. If both values match, the test passes. Otherwise, PyTest marks the test as failed and displays detailed information about the failure.

In this tutorial, you’ll learn what assertions are, how they work in Selenium with Python, and how to use the assert statement to validate your automation test results.


What are Assertions?

Assertions are statements that verify whether a specific condition is true during test execution.

If the condition evaluates to True, the test continues successfully.

If the condition evaluates to False, PyTest immediately stops the test and reports it as failed.

Example:

Perform Test Action

        │

        ▼

Get Actual Result

        │

        ▼

Compare with Expected Result

        │

 ┌──────┴──────┐
 │             │
 ▼             ▼

PASS         FAIL

Assertions help ensure that your Selenium automation scripts not only perform actions but also verify the correctness of the application’s behavior.


Why Use Assertions?

Assertions help you:

  • Verify application functionality.

  • Compare actual and expected results.

  • Detect defects automatically.

  • Prevent false-positive test results.

  • Improve automation reliability.

  • Generate meaningful test reports.


Common Assertion Examples

Verify equality:

assert title == "Dashboard"

Verify that text exists:

assert "Welcome" in message

Verify a boolean condition:

assert checkbox.is_selected()

Verify a numeric value:

assert total == 100

Example

from selenium import webdriver
from selenium.webdriver.common.by import By


# Topic: 39. Test Execution - Assertions
# Practice site: https://www.testmuai.com/selenium-playground/simple-form-demo
# Run: pytest -s 39_examples/test_03_assertions.py
#
# Assertions verify expected outcomes. If an assertion fails, PyTest marks the
# test as failed and shows a clear comparison in the report.


def test_assertions():
    driver = webdriver.Chrome()

    try:
        driver.get("https://www.testmuai.com/selenium-playground/simple-form-demo")

        first = driver.find_element(By.ID, "sum1")
        second = driver.find_element(By.ID, "sum2")
        first.send_keys("5")
        second.send_keys("7")
        driver.find_element(By.CSS_SELECTOR, "#gettotal > button").click()

        result = driver.find_element(By.ID, "addmessage").text
        assert result == "12"
        assert result.isdigit()
        assert int(result) == 12
    finally:
        driver.quit()

Understanding the Code

Import Required Libraries

from selenium import webdriver
from selenium.webdriver.common.by import By

These modules are required to launch the browser and locate web elements.


Create a Chrome Browser Instance

driver = webdriver.Chrome()

Starts a new Chrome browser session.


Open the Practice Website

driver.get(
    "https://www.testmuai.com/selenium-playground/simple-form-demo"
)

Navigates to the Simple Form Demo page.


Locate the Number Input Fields

first = driver.find_element(By.ID, "sum1")

second = driver.find_element(By.ID, "sum2")

Locates the two input fields where the numbers will be entered.


Enter the Numbers

first.send_keys("5")
second.send_keys("7")

Enters 5 into the first field and 7 into the second field.


Click the Get Total Button

driver.find_element(
    By.CSS_SELECTOR,
    "#gettotal > button"
).click()

Clicks the Get Total button to calculate the sum.


Read the Result

result = driver.find_element(
    By.ID,
    "addmessage"
).text

Retrieves the calculated result displayed on the webpage.


Verify the Expected Result

assert result == "12"

Verifies that the displayed result exactly matches the expected value 12.

If the values do not match, PyTest marks the test as failed.


Verify the Result Contains Only Digits

assert result.isdigit()

Uses the isdigit() method to confirm that the returned value contains only numeric characters.


Verify the Numeric Value

assert int(result) == 12

Converts the displayed text into an integer and verifies that its numeric value is 12.

Using multiple assertions helps validate different aspects of the application’s output.


Close the Browser

driver.quit()

Closes all browser windows and ends the WebDriver session.


Practical Example

Suppose you’re testing a login page.

The automation script:

  • Enters valid credentials.

  • Clicks the Login button.

  • Verifies that the user is redirected to the dashboard using an assert statement.


Automation Testing Example

Consider an online shopping application.

The automation script:

  • Adds a product to the shopping cart.

  • Retrieves the cart total.

  • Uses assertions to verify that the displayed total matches the expected value.


Real-World Example

Assertions are commonly used in:

  • Login verification

  • Registration forms

  • Search functionality

  • Shopping cart validation

  • Payment confirmation

  • Dashboard verification

  • Enterprise web applications

Nearly every Selenium automation test includes one or more assertions to validate application behavior.


Advantages of Assertions

  • Verify expected application behavior.

  • Detect failures immediately.

  • Improve automation reliability.

  • Produce clear failure reports.

  • Easy to understand and maintain.

  • Essential for automated testing.


Common Mistakes Beginners Make

Forgetting to Use Assertions

A Selenium script without assertions only performs actions.

Always verify the application’s response after performing an action.


Comparing Incorrect Values

Ensure that the expected value exactly matches the application’s actual output.

Even small differences such as spaces or letter casing can cause the test to fail.


Using Too Few Assertions

When appropriate, verify different aspects of the result instead of checking only a single condition.


Ignoring Failed Assertions

A failed assertion usually indicates either an application defect or an incorrect test expectation.

Always investigate the cause before modifying the test.


Best Practices

  • Verify every important application outcome.

  • Write clear and meaningful assertions.

  • Compare the correct expected values.

  • Keep assertions simple and readable.

  • Use multiple assertions only when they validate different conditions.

  • Always investigate failed assertions before updating the test.


Conclusion

Assertions are one of the most important parts of Selenium automation with Python. They confirm that the application behaves as expected after each automated action. By using the assert statement effectively, you can build reliable, meaningful, and maintainable automation tests that accurately validate your application’s functionality.


Frequently Asked Questions (FAQs)

What is an assertion?

An assertion is a statement that verifies whether an expected condition is true during test execution.


What happens if an assertion fails?

PyTest immediately marks the test as failed and displays information about the expected and actual results.


Can a test contain multiple assertions?

Yes.

A single test can include multiple assertions to verify different aspects of the application’s behavior.


Which keyword is used for assertions in PyTest?

PyTest uses Python’s built-in:

assert

statement to perform validations.


Why are assertions important in Selenium?

Assertions verify that the application behaves as expected after automation actions are performed, making your test results reliable and meaningful.


Key Takeaways

  • Assertions verify whether the application’s actual result matches the expected result.

  • PyTest uses Python’s built-in assert statement for validations.

  • Failed assertions immediately mark the test as failed.

  • Multiple assertions can validate different aspects of the same result.

  • Every meaningful Selenium automation test should include assertions.

  • Well-written assertions improve the reliability and quality of automation tests.