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)"); } }
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.
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.
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.
It's easier to do this:
driver.findElements(By.linkText("myLinkText")).size() < 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With