简体   繁体   中英

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.

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();

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.

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?");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM