Adan Vem
Adan Vem

Reputation: 3

Selenium 2 - checking error messages

I want to check error messages. These error messages appear only when my website encounters a problem.

My problem is that I use findElement in order to check the error message. So when something goes wrong, Selenium finds it, and everything is O.K.

But when it doesn't (meaning - my website is O.K with no problems) - then Selenium indicates that it doesn't find the element, and rises an exception.

Any idea?

Upvotes: 0

Views: 1450

Answers (3)

Khyati Sehgal
Khyati Sehgal

Reputation: 385

1.For this you should design your test case in such a way that you writes code to check error message only when you are sure that you will get error message.

2.But the point is why are you checking for error message when you know that there will be no problem and code will run fine.

3.If you doesn't know that error will occur.. You can place the risky code in try block and write a catch block which will find error message and check it.

Upvotes: 0

VolkerK
VolkerK

Reputation: 1510

Take a look at the answer Selenium Webdriver NoSuchElementException

It suggests the following (I've adapted it a bit for your needs) :

List<WebElement> errorElements = driver.findElements(By.id("ERROR_ID"));
if (!errorElements.empty()) {
   // Tests your errors
}

Upvotes: 0

Prashant Shukla
Prashant Shukla

Reputation: 1389

you can surround the findElement in a try-catch block, which will do nothing if the element is not found. e.g.

    private boolean isElementPresent(By by) {
                    try {
                        driver.findElement(by);
                        return true;
                    } catch (NoSuchElementException e) {
                        return false;
                        //or do nothing
                    }
                }

Upvotes: 1

Related Questions