How to verify/compare 2 values in Selenium?

2 min read 06-10-2024
How to verify/compare 2 values in Selenium?


Asserting Your Way to Success: Verifying Values in Selenium

Selenium is a powerful tool for automating web browser interactions, but its true power lies in its ability to verify elements and behaviors on a webpage. This is where assertions come into play. Assertions are crucial for testing, allowing you to compare expected values with actual values found on the page.

Imagine you're building an online store. You want to ensure that a product's price is correctly displayed on the product page. This is where Selenium's assertion capabilities shine!

The Scenario:

Let's assume you have a simple webpage with a product listed:

HTML:

<div class="product-details">
  <h2 class="product-name">Awesome T-shirt</h2>
  <p class="product-price">$20.00</p>
</div>

You want to verify that the price displayed is indeed $20.00. Here's how you would do it using Selenium (Python example):

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

driver = webdriver.Chrome()
driver.get("https://your-website.com/product-page")

# Get the price element
price_element = driver.find_element(By.CSS_SELECTOR, ".product-price")

# Extract the price text
actual_price = price_element.text

# Expected price
expected_price = "$20.00"

# Assert the prices are equal
assert actual_price == expected_price

print("Price verification successful!")

driver.quit()

In this code, we first locate the price element using its CSS selector. We then extract the text value of the element, which is the actual price displayed. Finally, we use the assert statement to compare the actual price with the expected price. If they match, the assertion passes, and the test continues. If not, the assertion fails, indicating an error.

Beyond Simple Comparisons:

While comparing exact string values is useful, Selenium offers more advanced assertion options:

  • assert_not_equal: Verify two values are not equal.
  • assert_true and assert_false: Verify a condition is true or false.
  • assert_in: Verify if a string is present within another string.
  • assert_not_in: Verify if a string is not present within another string.

Examples:

  • Verifying the presence of an element:
    assert driver.find_element(By.ID, "login-button").is_displayed() 
    
  • Verifying the absence of an error message:
    assert driver.find_elements(By.CSS_SELECTOR, ".error-message") == []
    

Key Takeaways:

  • Assertions are crucial for verifying webpage behavior and ensuring the functionality of your web application.
  • Use assert statements to compare expected values with actual values found on the webpage.
  • Selenium offers a variety of assertion methods for different verification needs.

Resources:

By mastering assertions, you can confidently test your web applications and ensure a smooth and reliable user experience.