Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that a WebElement is not present using Selenium WebDriver with java

In tests that I write, if I want to assert a WebElement is present on the page, I can do a simple:

driver.findElement(By.linkText("Test Search")); 

This will pass if it exists and it will bomb out if it does not exist. But now I want to assert that a link does not exist. I am unclear how to do this since the code above does not return a boolean.

EDIT This is how I came up with my own fix, I'm wondering if there's a better way out there still.

public static void assertLinkNotPresent (WebDriver driver, String text) throws Exception { List<WebElement> bob = driver.findElements(By.linkText(text));   if (bob.isEmpty() == false) {     throw new Exception (text + " (Link is present)");   } } 
like image 249
True_Blue Avatar asked Jul 19 '10 17:07

True_Blue


People also ask

How do you assert that an element is not present in Selenium?

We can verify if an element does not exist in Selenium webdriver. To achieve this, we shall use the method getPageSource which gets the entire page source. So we can obtain a complete page source and check if the text of the element exists.

How do you know if Webelement is not present?

Using driver.findElements() method returns a list of webElements located by the “By Locator” passed as parameter. If element is found then it returns a list of non-zero webElements else it returns a size 0 list. Thus, checking the size of the list can be used to check for the presence and absence of element.

How do you assert if an element is present?

To make sure that an element is present you can do the following: driver. findElements(By.id("id")); That will return an array, if that array size is > 0 then the element/s is present.


1 Answers

It's easier to do this:

driver.findElements(By.linkText("myLinkText")).size() < 1 
like image 73
Sarhanis Avatar answered Oct 21 '22 14:10

Sarhanis