Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify an error message using selenium web driver

Tags:

I want to verify the error message displaying after login failed. Specifically, I want to verify the text with "Invalid username or password".

This is the html code.

<div id="statusMsg">
  <div class="alert in fade alert-error" style="opacity: 1;">
    <a class="close" data-dismiss="alert">×</a>
      Invalid username or password
  </div>
</div>

This is the code I tried.

String actualMsg=driver2.findElement(By.xpath("//div[@id='statusMsg']/div")).getText()
String errorMsg= "× Invalid username or password";

if(actualError.equals(errorMsg)) {
    System.out.println("Test Case Passed");
}else{
    System.out.println("Test Case Failed");
};

The output is always "Test Case Failed".

Is There a way to fix this?

like image 999
Darshani Kaushalya Avatar asked Dec 21 '17 06:12

Darshani Kaushalya


People also ask

How can I verify error message on a webpage using Selenium Webdriver?

We can verify error messages on a webpage using Selenium webdriver using the Assertion. In case, the actual and expected values do not match, an Assertion Error is thrown.

Can you verify in test using Selenium?

We can verify the color of a webelement in Selenium webdriver using the getCssValue method and then pass color as a parameter to it.

What are verify commands in Selenium?

We can use following two commands to verify the presence of an element: verifyElementPresent – returns TRUE if the specified element was FOUND in the page; FALSE if otherwise. verifyElementNotPresent – returns TRUE if the specified element was NOT FOUND anywhere in the page; FALSE if it is present.


1 Answers

To extract the text Invalid username or password you have to reach to the <div> tag as follows :

String actualMsg = driver2.findElement(By.xpath("//div[@id='statusMsg']/div[@class='alert in fade alert-error']")).getAttribute("innerHTML");

Next your expected error message is :

String errorMsg = "× Invalid username or password";

As x is within <a> tag and Invalid username or password is within <div> tag the validation process will need a bit of String manipulation. To make the validation simpler you can reduce the expected error message as follows :

String errorMsg = "Invalid username or password";

Now you can use the following code block to verify if the actualMsg contains errorMsg as follows :

if(actualMsg.contains(errorMsg)) 
{
    System.out.println("Test Case Passed");
}else
{
    System.out.println("Test Case Failed");
};
like image 60
undetected Selenium Avatar answered Sep 20 '22 12:09

undetected Selenium