Selenium Assertions – Assert and Verify Method

FREE Online Courses: Transform Your Career – Enroll for Free!

One of the essential parts of Selenium testing is the ability to verify whether the test cases pass or fail. This is where assertions come into play. Assertions are an integral part of Selenium automation testing, and they help to validate that the test cases are working correctly. In this article, we will learn about assert and verify methods in selenium.

What are Selenium Assertions?

Selenium Assertions are commands that allow you to verify whether a particular condition is true or false in your test script. Assertions are used to validate the expected results of the test case against the actual results obtained. Assertions play a vital role in Selenium automation testing because they help you ensure that the web application behaves as expected.

When you write a Selenium test script, you expect certain things to happen when you execute the script. For example, when you click on a button, you expect a new page to load. In such cases, you need to use assertions to verify that the expected behavior occurred. If the expected behavior did not occur, the test case fails, and you need to investigate the cause of the failure.

Categories of Assertions in Selenium

Assertions are an essential part of test automation, as they help in verifying whether the expected results match the actual results. There are two main types of assertions: hard assertions and soft assertions.

1. Hard Assertions in Selenium:

Hard assertions are used to test the expected outcome of a test case. If the assertion fails, the test case is immediately marked as failed, and the test execution stops. Hard assertions are considered “hard” because they halt the test execution if the expected outcome does not match the actual outcome. Examples of hard assertions include AssertEquals, AssertTrue, AssertFalse, and AssertNotNull.

There are various methods of Hard Assertions. Some of them are as follows:

a. AssertEquals: This assertion method is used to compare expected and actual values. It checks whether the expected value is equal to the actual value or not. If the values are not equal, then the assertion fails and the test case will be marked as failed.

b. AssertNotEquals: This assertion method is used to compare expected and actual values. It checks whether the expected value is not equal to the actual value or not. If the values are equal, then the assertion fails and the test case will be marked as failed.

c. AssertTrue: This assertion method is used to verify a condition that should be true. If the condition is true, then the test case passes. If the condition is false, then the assertion fails and the test case will be marked as failed.

d. AssertFalse: This assertion method is used to verify a condition that should be false. If the condition is false, then the test case passes. If the condition is true, then the assertion fails and the test case will be marked as failed.

e. AssertNull: This assertion method is used to verify that a value is null. If the value is null, then the test case passes. If the value is not null, then the assertion fails and the test case will be marked as failed.

f. AssertNotNull: This assertion method is used to verify that a value is not null. If the value is not null, then the test case passes. If the value is null, then the assertion fails and the test case will be marked as failed.

2. Selenium Soft Assertions:

Soft assertions, also known as “assertion softening,” are used to verify multiple conditions within a test case. Even if the assertion fails, the test case continues to execute, and all the failed assertions are reported at the end of the test. Soft assertions are considered “soft” because they do not halt the test execution if an assertion fails, and the test continues to execute. Examples of soft assertions include AssertAll, AssertThat, and Verify.

Some methods of soft assertions include:

a. assertAll(): This method is used to assert all the recorded failures in a test case. It checks if any assertion has failed, and if so, it throws an Assertion Error containing all the failure messages.

b. assertThat(): This method is used to perform various types of soft assertions on the actual value against the expected value using various matcher methods. The test continues to execute even if an assertion fails and reports all the failed assertions at the end.

c. fail(): This method is used to record a failure in a test case without stopping the execution of the test. This method can be used to add a custom message to a soft assertion failure.

Overall, the choice between hard and soft assertions depends on the testing requirements and the nature of the test case. Hard assertions are suitable for situations where the test case cannot proceed if an expected condition fails. Soft assertions are more suitable for scenarios where it is necessary to validate multiple conditions within a single test case.

Difference between Selenium Hard and Soft Assertions

Hard AssertionsSoft Assertions
FailureImmediately fails the test case and stops test executionContinues executing the test case even if assertion fails, and reports all failed assertions at the end
UsageUsed to test the expected outcome of a test caseUsed to verify multiple conditions within a single test case
Type of AssertionTypically uses assert methods like assertEquals, assertTrue, etc.Typically uses methods like assertAll, assertThat, verify, etc.
ImpactHas a greater impact on test executionHas a lower impact on test execution
ValidationUsed to validate the state of a single element or a small group of elementsUsed to validate the state of multiple elements or a larger group of elements

Selenium Assert Methods

There are various types of Selenium Assertions that you can use in your test scripts. Some of the most commonly used Selenium Assertions are:

1. assertEqual: The assertEqual method compares two values and returns True if they are equal, or False if they are not.

2. assertNotEqual: The assertNotEqual method compares two values and returns True if they are not equal, or False if they are.

3. assertTrue: The assertTrue method checks whether a given condition is true or not. If the condition is true, it returns True; otherwise, it raises an assertion error.

4. assertFalse: The assertFalse method checks whether a given condition is false or not. If the condition is false, it returns True; otherwise, it raises an assertion error.

5. assertIn: The assertIn method checks whether a given item is present in a list or not. If the item is present, it returns True; otherwise, it raises an assertion error.

6. assertNotIn: The assertNotIn method checks whether a given item is not present in a list or not. If the item is not present, it returns True; otherwise, it raises an assertion error.

7. assertIs: The assertIs method checks whether two objects are the same or not. If the objects are the same, it returns True; otherwise, it raises an assertion error.

8. assertIsNot: The assertIsNot method checks whether two objects are not the same or not. If the objects are not the same, it returns True; otherwise, it raises an assertion error.

9. assertRaises: The assertRaises method checks whether a specific exception is raised or not. If the exception is raised, it returns True; otherwise, it raises an assertion error.

10. assertRaisesRegex: The assertRaisesRegex method checks whether a specific exception is raised with a matching regular expression or not. If the exception is raised with a matching regular expression, it returns True; otherwise, it raises an assertion error.

Using Selenium Assertions in Python:

Let us now look at how to use Selenium Assertions in Python. For this tutorial, we will be using the Python Selenium module and the Chrome driver. Firstly You need to download the Chrome driver.

Then we need to install the Selenium module using the following command:

pip install selenium

After installing the Selenium module, we need to import the required libraries in our Python script:

from selenium import webdriver
from selenium.webdriver.common.keys import *

Now, let’s create a simple Selenium test script that searches for a string on Google and verifies the page title:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()

driver.get("https://www.google.com")

search_box = driver.find_element_by_name("q")
search_box.send_keys("Selenium Assertions")

search_box.send_keys(Keys.RETURN)

time.sleep(5)

assert "Selenium Assertions - Google Search" in driver.title

driver.quit()

In the above script, we first create a new instance of the Chrome driver and navigate to the Google website. We then find the search box element and enter the search term “Selenium Assertions.” We press Enter to perform the search and wait for the page to load.

Finally, we use the assert statement to verify that the page title contains the search term “Selenium Assertions.” If the page title does not contain the search term, the assert statement will raise an AssertionError and the test case will fail.

Using Selenium Assertions in Java:

Now, let’s look at how to use Selenium Assertions in Java. For this tutorial, we will be using Eclipse as our Java IDE and the Chrome driver.

First, we need to download Selenium Java client driver. We also need to download the Chrome driver.

Once we have downloaded the required drivers, we need to create a new Java project in Eclipse. Then add the Selenium Java client driver and Chrome driver to the project build path.

Next, we can create a simple Selenium test script that searches for a string on Google and verifies the page title:

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.Assert;


public class SeleniumAssertionsExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("Selenium Assertions" + Keys.RETURN);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(driver.getTitle().contains("Selenium Assertions - Google Search"));
driver.quit();
}
}

In the above script, we first set the Chrome driver path and create a new instance of the Chrome driver. We navigate to the Google website and find the search box element. Then eenter the search term “Selenium Assertions” and press Enter to perform the search. We wait for the page to load and then use the Assert statement to verify that the page title contains the search term “Selenium Assertions.” If the page title does not contain the search term, the Assert statement will throw an AssertionError and the test case will fail.

Conclusion:

Selenium Assertions play a vital role in Selenium automation testing as they help to verify whether the test cases pass or fail. There are various types of Selenium Assertions available, such as AssertTrue, AssertFalse, AssertEquals, etc. It can be used to verify different aspects of a web page.

In this article, we learned about Selenium Assertions and how to use them in Python and Java. We saw how to create a simple Selenium test script that searches for a string on Google and verifies the page title using Assertions.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *