When i use Assert.assertFalse(), to check the absence of an element, my scripts are getting failed - selenium

Assert.assertFalse(driver.findElement(By.xpath("element's xpath")).isDisplayed(),
"Bug!! The element is appeared");
When i run my code with the above script, my scripts are failing with the statement like "can't find the element, (Which is mentioned int he element's xpath)"
Now what i have to do? My notion is to verify the element is not present in the screen

findElement throws an exception if no matching element is found, so you tests will fail with the selenium exception, not JUnit.
you can use findElements (which doesn't throws exceptions) and check that the returned list length is equals to 0
See details in the Selenium documentation

I see that this has been asked a long while ago, but perhaps someone who is looking for a solution to the similar problem will find it useful now.
I have a certain way to deal with such problems, not sure if it's a good way to do this, but at least it makes sense and does the job.
Firstly, I usually define a separate method for finding such elements:
private static WebElement element = null;
public static WebElement findYourElement(WebDriver driver) {
try {
element = driver.findElement(By.xpath("your_xpath_here"));
}
catch(NoSuchElementException e) {
System.out.println(e.getMessage());
element = null;
return element;
}
return element;
}
You can see here that the possible NoSuchElementException is being caught should it be thrown. In case of exception, the value for "element" is also set to null, since in my program there might be values from previous elements stored here and we don't to have any other non-relevant elements here.
Next comes the assertion:
Assert.assertFalse(findYourElement != null, "Bug!! The element is there!"
Here the assertFalse method fails if the element returned by the findYourElement is not empty, yielding a True result from element != null comparison and making assertFalse fail, as it is expecting to have a false value in order to continue.
You could just as well go:
Assert.assertTrue(findYourElement = null, "Bug!! The element is there!"
I think that such solution helps to keep things well organized, but on the other hand it may be larger in terms of code volume and more complicated too. It also depends how good are you with Java and if you are willing to mess with the exceptions.
I am no Java guru myself, so any contribution towards improving my current solution will be much appreciated!

Do this small change, it definitely works
Assert.assertTrue(driver.findElements(By.xpath("element's xpath")).size()<1;,
"Bug!! The element is appeared");

Related

How to get false if element is not present on page in Selenium webdriver

I am working with automation now and again have faced a problem. In general, I have logic in my code where I need to check for the existence of an element and next step will depend on the result of checking. But base instruments of Selenium return only boolean true otherwise NoSuchElementException. But I need "false".
As on my previous project, I use simple wrapper for solving this problem now:
private boolean isDisplayedOnPage(WebElementFacade wef){
try{
return wef.isDisplayed();
} catch (NoSuchElementException nsee){
return false;
}
}
It works perfectly but the use of the exception confuses me. Also, I read about "wait" but it doesn't return false as well, only lets me ignore the exception. Are there built-in instruments for solving this problem in Selenium? Or maybe someone can offer a more elegant way to solve it?
One of the core tenets of the raw WebDriver API is the expectation that the user knows the state of the DOM for the page being automated. This means that, in the logic of the API, calling findElement using a locator of an element that doesn’t exist is an exceptional condition, making the throwing of an exception perfectly legitimate. While one could argue that the expectation built into the API behavior is faulty, that’s beyond the scope of this answer. If you need Boolean logic for whether an element exists, you need a wrapper method, as you’ve already discovered. Within that wrapper method, you have two choices:
Use findElement and catch the NoSuchElementException. Note that using WebDriverWait implicitly catches this exception for you, so is a semantic equivalent.
Use findElements (note the "s"), which returns an empty list without throwing an exception if the element doesn’t exist.
Boolean bool = my_driver.findElements(By.id("my element id")).size()>0;
this will help you.
An unclean workaround could be to check the DOM for a unique String that symbolizes your WebElement and then write into a boolean if it could be found.
This loop will check the DOM for the string around every second for 60 times with refreshing the page if nothing was found:
for (int i= 0; i <60; i++){
String pageSource = browser.getPageSource().toString();
boolean elementThere = pageSource.contains("uniqueStringOfElement");
if (elementThere){
browser.WebElement.click()
break;
}
else {
Thread.sleep(1000);
browser.navigate().refresh();
}
}

How long will FindElements wait?

Say the implicit timeout is 10 sec.
Then I execute an FindElements (plural!) with some XPath.
Question
How long FindElements waits, until deciding to return? (please disregard any deferred execution feature of any language. Then I rephrase my question to FindElements(...).Count())
Reasoning the question
I suppose in case there is no match then it will wait for 10 secs.
However if there is at least one match, then will it return instantly? This case we will miss a possible following elements if they populated by the page's javascript during the 10 sec.
My general problem is the following:
We do not want to wait for the timeout unconditionally all the time(it would be bad#1)
We do not want to miss any match what is available within the timeout (it would be bad #2
Question rephrased
Which bad (#1 or #2) is the reality, regarding FindElements behaviour?
This method is affected by the 'implicit wait' times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
What you could do, so that you do not miss any matches is to wait for the page to completely load by checking the document.readyState to be equal to complete and then call the driver.findElements method.
public void waitForPageLoaded() {
ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
}
};

Check a defined WebElement in a Page Object

My first question here. I hope this question is not already answered. I previously searched if it exists, sorry if I'm wrong.
My question is the next. I have this webelement in a PageObject class for automated tests:
//Customer filter
#FindBy(id = "customer_filter")
private WebElement customerFilter;
Later I try to check if it's present or not, like this:
Boolean test = customerFilter.isDisplayed();
But it doesn't work, it says the webelement is not present when actually is not present, and the test ends. I've also tried with isEnabled() and isSelected(). I have to use instead the next code so everything works:
Boolean isPresent = driver.findElements(By.id("customer_filter")).size() > 0;
if(isPresent){
Is there a way to use webelement directly so I don't have to continuosly use the id locator?
Thanks in advance!!!
Edit: Looking for a little more information, I found this thread about the same problem, but it wasn't resolved: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/1880
When you use the "#FindBy" annotation, it returns a WebElement Proxy. The WebElementProxy is a wrapper around webelement, and has a "UnderlyingWebElement" property, which is what you're looking for.
https://github.com/barancev/webdriver-samples/blob/master/src/ru/st/selenium/WebElementProxy.java#L141
How you can leverage this, is you can do some creative typecasting to access some of these methods that are not in the IWebElement interface.
if( ((WebElementProxy)customerFilter).getWrappedElement() != null) {
//do something
}
Please refer to this post:post
Also have in mind that when you're checking if .size()>0, this has nothing to do with either visible or presented element. This collection contains all element in the DOM that are matching the criteria.
My advise is to create a method that you call each time with parameter the element that you're looking for.

how to check if a web form element exists with selenium

I need to check if a form element exists in my current web page with selenium.
Does anybody know how to do?
There are two ways to do this. Either use lefthandedgoat's version catching an exception, or use the FindElements method and check it's size, so something like (in C# using LINQ):
public bool IsElementPresent(By selector)
{
return driver.FindElements(selector).Any();
}
Either option will work fine, there is not really much different. I personally use the other way, but wanted to make sure you knew there are generally two ways to do this. You didn't mention a language, so let us know if there is a specific language you are using.
It is worth noting that underneath, when you do a FindElement() in Selenium, it is performing this method.
In the C# version of selenium it will throw an exception if the element does not exist. You could do something like this
public bool Exists(string cssSelector)
{
try
{
browser.FindElement(By.CssSelector(cssSelector));
return true
}
catch (Exception ex){}
return false;
}
var exists = Exists("form");
I am not sure how the webdriver behaves in other languages.
you can use pair of methods:
input.findElements(By.xpath("//....blablalba....")).size() > 0
driver.findElement(By.xpath("//....blablalba....")).isDisplayed()

Is it meaningful to verifyText() on an element that has just had type() executed on it?

I'm curious about whether the following functional test is possible. I'm working with PHPUnit_Extensions_SeleniumTestCase with Selenium-RC here, but the principle (I think) should apply everywhere.
Suppose I execute the following command on a particular div:
function testInput() {
$locator = $this->get_magic_locator(); // for the sake of abstraction
$this->type( $locator, "Beatles" ); // Selenium API call
$this->verifyText( $locator, "Beatles" ); // Selenium API call
}
Conceptually, I feel that this test should work. I'm entering data into a particular field, and I simply want to verify that the text now exists as entered.
However, the results of my test (the verifyText assertion fails) suggest that the content of the $locator element are empty, even after input.
There was 1 failure:
1) test::testInput
Failed asserting that <string:> matches PCRE pattern "/Beatles/".`
Has anyone else tried anything like this? Should it work? Am I making a simple mistake?
You should use verifyValue(locator,texttoverify) rather than verifyText(locator,value) for validating the textbox values
To answer your initial question ("Is it meaningful ..."), well, maybe. What you're testing at that point is the browser's ability to respond to keystrokes, which would be sort of lame. Unless you've got some JavaScript code wired to some of the field's properties, in which case it might be sort of important.
Standard programmer's answer - "It depends".