Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I verify that an element does not exist in Selenium 2

Tags:

In Selenium 2 I want to ensure that an element on the page that the driver has loaded does not exist. I'm including my naive implementation here.

    WebElement deleteLink = null;     try {         deleteLink = driver.findElement(By.className("commentEdit"));     } catch (NoSuchElementException e) {      }     assertTrue(deleteLink != null); 

Is there a more elegant way that basically verifies to assert that NoSuchElementException was thrown?

like image 860
Han Avatar asked Jun 15 '11 05:06

Han


People also ask

How do you check if an element is not present in a page?

isDisplayed() is the method used to verify a presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.

How do I check if a WebElement is null?

Below is my code:WebElement deleteLink = null; try { deleteLink = driver. findElement(By. className("commentEdit")); } catch (NoSuchElementException e) { } assertTrue(deleteLink != null);

How can you tell if an element is invisibility in Selenium?

Below is the syntax which is used for checking that an element with text is either invisible or not present on the DOM. WebDriverWait wait = new WebDriverWait(driver, waitTime); wait. until(ExpectedConditions. invisibilityOfElementWithText(by, strText));


2 Answers

If you are testing using junit and that is the only thing you are testing you could make the test expect an exception using

@Test (expected=NoSuchElementException.class) public void someTest() {     driver.findElement(By.className("commentEdit")); } 

Or you could use the findElements method that returns an list of elements or an empty list if none are found (does not throw NoSuchElementException):

... List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit")); assertTrue(deleteLinks.isEmpty()); ... 

or

.... assertTrue(driver.findElements(By.className("commentEdit")).isEmpty()); .... 
like image 107
mark-cs Avatar answered Oct 05 '22 10:10

mark-cs


You can use this:

Boolean exist = driver.findElements(By.whatever(whatever)).size() == 0; 

If it doesn't exist will return true.

like image 44
Shehab Mostafa Avatar answered Oct 05 '22 09:10

Shehab Mostafa