How can I verify Error Message on a webpage using Selenium Webdriver?
Last Updated :
02 Sep, 2024
Selenium WebDriver is an essential tool for automating web application testing, allowing testers to ensure that applications function correctly and efficiently. One critical aspect of this testing is verifying error messages, which are crucial for user feedback, especially when invalid inputs are provided or issues arise.
In this guide, we'll explore how to verify an error message using Selenium WebDriver by focusing on a practical example with the GeeksforGeeks (GFG) login page. This demonstration will help you understand the process of checking for error messages to ensure your web application's error-handling mechanisms work as expected.
Steps to Verify the Error Message
Suppose we are testing the login functionality of the GFG website. If a user enters invalid credentials (e.g., incorrect email or password), an error message should be displayed. Our goal is to verify that this error message appears as expected.
- Set up Selenium WebDriver: Ensure that you have installed the necessary dependencies, including the Selenium package and WebDriver for your browser (e.g., Chrome Driver).
- Locate the necessary elements: Use Selenium to locate the input fields for the username and password, as well as the element that displays the error message.
- Submit invalid credentials: Enter incorrect login details and submit the form to trigger the error message.
- Capture and verify the error message: Retrieve the text of the error message displayed on the webpage and compare it with the expected message.
Example
Below is the Python code that demonstrates the steps mentioned above to verify the error message on the GeeksforGeeks login page using Selenium WebDriver.
Java
package com.example.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class VerifyErrorMessage {
public static void main(String[] args) {
// Set up ChromeDriver using WebDriverManager
WebDriverManager.chromedriver().setup();
// Initialize ChromeDriver instance
WebDriver driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
try {
// Navigate to the GFG login page
driver.get("https://auth.geeksforgeeks.org/");
// Locate the username and password fields
WebElement usernameField = driver.findElement(By.id("luser"));
WebElement passwordField = driver.findElement(By.id("password"));
// Enter invalid credentials
usernameField.sendKeys("invalid_username");
passwordField.sendKeys("invalid_password");
passwordField.submit();
// Introduce a small delay to allow the error message to load
Thread.sleep(3000);
// Capture the error message
WebElement errorMessage = driver.findElement(By.cssSelector(".alert.alert-danger"));
String actualMessage = errorMessage.getText();
// Verify the error message
String expectedMessage = "Invalid email or password.";
if (actualMessage.equals(expectedMessage)) {
System.out.println("Test Passed: Error message verified successfully.");
} else {
System.out.println("Test Failed: Expected message '" + expectedMessage + "', but got '" + actualMessage + "'.");
}
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
} finally {
// Close the WebDriver
driver.quit();
}
}
}
Explanation of the Code
- We start by initializing the WebDriver for Chrome (you can use other browsers like Firefox or Edge by downloading the respective WebDriver).
- The get() method is used to navigate to the GFG login page.
- Using Selenium's find_element() method, we locate the username and password input fields by their HTML IDs (luser and password respectively).
- Invalid credentials are entered into the form, and the RETURN key is pressed to submit it.
- A small delay (3 seconds) is introduced to allow the page to load the error message after submission.
- The error message is captured using the css Selector associated with it (.alert.alert-dange).
- The captured error message is compared with the expected error message using an assert statement. If the messages match, the test passes; otherwise, an assertion error is raised.
- Finally, the WebDriver is closed to end the session.
Output
If the test runs successfully, the error message will be verified without any issues. If the assertion fails, an error message will be displayed indicating the mismatch between the expected and actual error messages.
VerifyErrorMessage outputConclusion
In this article, we've learned how to use Selenium WebDriver to verify error messages on the GeeksforGeeks (GFG) login page. By automating the process of entering invalid credentials and capturing the resulting error message, we ensure that the application provides accurate and appropriate feedback to users. This approach is vital for maintaining a smooth user experience and robust error handling.
With Selenium WebDriver, you can effectively test and validate error messages across various web applications, enhancing the reliability and usability of your software.
Similar Reads
How to refresh a webpage using java Selenium Webdriver? Refreshing a webpage is often necessary when you want to ensure that your tests or interactions are working with the latest content or to reset the state of a web page during automation. Selenium WebDriver makes this task straightforward with various methods available in Java. This article will demo
3 min read
How to Click on a Hyperlink Using Java Selenium WebDriver? An open-source tool that is used to automate the browser is known as Selenium. Automation reduces human effort and makes the work comparatively easier. There are numerous circumstances in which the user wants to open a new page or perform a certain action with the click of the hyperlink. In this art
4 min read
Reading JavaScript variables using Selenium WebDriver In web automation testing, interacting with JavaScript variables on a webpage can be essential for validating specific conditions. Selenium WebDriver provides a way to execute JavaScript directly on the browser using the `executeScript()` method. This feature allows us to read JavaScript variables a
2 min read
How to get Response Status Code with Selenium WebDriver? In web automation and testing, obtaining the HTTP response status code is crucial for validating the accessibility and health of web pages. While Selenium WebDriver is widely recognized for its powerful capabilities in automating browser interactions, it does not directly provide methods for fetchin
4 min read
Find Web Elements using Selenium WebDriver We can identify web elements in the web page using the following two tools: Developer Tools FireBug and FirePath Developer Tools - Right-click on the web page. Navigate to inspect element to find the developer's tool. Note: There are some websites where the right-click is disabled. eg. IRCTC, bankin
4 min read
Wait Until Page Is Loaded With Selenium WebDriver For Python Selenium is an automation tool or a web framework used mainly in testing web applications across various browsers. Apart from testing web applications, we can also perform various tasks with selenium. With the help of selenium, we can also perform various web related tasks such as web scraping, web
5 min read
Handle Firefox Not Responding While Using Selenium WebDriver using java? During the usage of Selenium WebDriver with Java and internet applications, the problem of having a âFirefox Not Respondingâ error may be quite frequent when running lengthy or detailed tests. This problem tends to interfere with test flows and thus fails in test cases and returns wrong results. To
3 min read
How to click a button on webpage using Selenium? This article is all about how to click any button using Selenium on a webpage and many more concepts related to the same which are discussed below. Table of Content What is Selenium? How to click on a button using Selenium Conclusion Frequently Asked Questions on How to click a button on webpage usi
2 min read
How Selenium WebDriver Can be Used to Detect Broken Links? Selenium is a widely used tool for testing any websites or other applications. It is a suite of all testing software. There are many segments of Selenium. Like there is Selenium Web Driver, Selenium IDE, Selenium RC, etc. Selenium IDE is used by those users who are coming from a non-computer science
11 min read
How to Take a Screenshot in Selenium WebDriver Using Java? Selenium WebDriver is a collection of open-source APIs used to automate a web application's testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used t
3 min read