Rajesh Om
Rajesh Om

Reputation: 518

How to handle dynamic text (Success and Failure text)using Selenium WebDriver

I am facing one problem in Selenium WebDriver script ,in my logic i want to verify form submission with below scenarios.

1.Submit form with already register details - Details already exists
2.Submit Form with new details - Successfully added.

Now my problem is both the text messages are having different locators as below

driver.findElement(By.xpath("//div[@class='alert alert-success']")).getText();
driver.findElement(By.xpath("//div[@class='alert alert-error']")).getText();

Now i need selenium code in java as code automatically handle the text based on text on screen to verify whether my test case is pass/fail.Please provide how to write this type of situation in a webpage.

Simple I want to verify whether customer is register in a system ,if not i should register in a system based on Message on screen.

When i use both the xpaths then it is finding one text in a system and another not exist then it is giving element not found exception,please suggest.

Upvotes: 2

Views: 4452

Answers (3)

Xwris Stoixeia
Xwris Stoixeia

Reputation: 1861

You can assign the result of your Xpath search to a String variable and then regulate your flow from there. I've seen, one answer has already been given for CSS but as long as your original post refers to Xpath here is the Xpath solution:

String isFormAlreadySubmitted = driver.findElement(By.xpath("//div[@class='alert alert-error' or @class='alert alert-success']")).getText();

From this point onwards you can direct the flow with a simple if statement:

if(isFormAlreadySubmitted.equals("Details already exist"){
System.out.println("Form already submitted!");
}
else if(isFormAlreadySubmitted.equals("Successfully added"){
System.out.println("Successfully added a new record!");
}
else{
System.out.println("Something went wrong! Couldn't get alert text, is alert present?");
}

Upvotes: 1

Guy
Guy

Reputation: 50899

You can use or condition with cssSelector. This will check for both options and return the first one found

driver.findElement(By.cssSelector(".alert.alert-success, .alert.alert-error")).getText();

Upvotes: 6

acikojevic
acikojevic

Reputation: 945

If one message exists and other doesn't, then you are getting NoSuchelementException because other message is not present, that's expected behavior. You should catch NoSuchelementException if you don't want your tests to fail in that case. You could even try with driver.findElement(By.xpath("//div[contains(@class, 'alert']")).getText(); and verify which text you got but I can't be sure will it work because I don't know how your page behaves and looks like.

Upvotes: 1

Related Questions