if/else statement fail - java

I'm using if/else statements as below, but the script fails in Selenium WebDriver. Here, for one test case the if statement works but, for another test case, the else one doesn't.
if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()){
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
}
else
{
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
}

Im not good at Java, so im putting the steps. Give try.
1. First Find elements seperately.
2. Now check if 'top' is not null and then check for is displayed and can continue further .Pseudo code below
IWebElement top= driver.findelement( put you locator top here )
IWebElement bottom = driver.findelement( put you bottom here)
if(top!=null)
{
if(top.IsDisplayed)
{
top.click()
}
}
else
{
if(bottom!=null)
{
bottom.click()
}
}

we need to click on element "div.Tooltip__body.Tooltip__body--top" if it is displayed. if not then need to click on "div.Tooltip__body.Tooltip__body--bottom"
If we use .isDisplayed to check element displayed or not, in any case element is not there, it will throw exception. that's why we need to handle this exception by using try/catch.
try{
//if element is displayed, then click it
if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()==true){
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
}
}catch(Exception e){
//exception occurred as element (top) is not available.
//so i need to click on bottom
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
//if required we can collect exception : e.getMessage()
}
Thanks

try
{
if (driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).isDisplayed()==true)
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--top")).click();
}
catch(Exception ex)
{
driver.findElement(By.cssSelector("div.Tooltip__body.Tooltip__body--bottom")).click();
}

Related

Delete a record from web table scenario in Selenium Webdriver

I am writing an automation script and one of the scenarios I wish to automate is to delete a record from grid, now what I am doing is finding the xpath of the list of delete buttons in the grid, and I'm hitting an 'if' condition where I state that if the delete button is displayed on page delete the first record or else driver.close(); but I guess Selenium isn't checking the condition, it is directly showing me NoSuchElement exception. Can someone please suggest me a better way or some other alternative to automate such a scenario. The code I'm using:=
//resourceSchedulePage - Class object
//clickDeleteResourceScheduleDataBtn() - method that returns the WebElement
schedulerPage.clickResourceSchedule().click();
logger.info("Resource schedule link is clicked");
Thread.sleep(500);
if(resourceSchedulePage.clickDeleteResourceScheduleDataBtn().isDisplayed())
{
resourceSchedulePage.clickDeleteResourceScheduleDataBtn().click();
Thread.sleep(500);
}
else
{
driver.close();
}
Implementation :
#FindBy(xpath="//*[#id=\"gridResourceSchedule\"]//td[6]/a[2]")
WebElement deleteResourceScheduleBtn;
public WebElement clickDeleteResourceScheduleDataBtn() throws InterruptedException {
synchronized (driver) {
driver.wait(1000); }
return deleteResourceScheduleBtn; }
As explained by #pburgr, here is the implementation for findElements
if (driver.findElements(By.xpath("Delete button xpath")).size() > 0 ) {
System.out.println("Delete button is avilable");
// you can click on delete here, or whatever you wanna do.
}
else {
System.out.println("Delete button isn't avilable");
driver.close();
}
also there is a way to handle this situation which is try catch block.
element.isDisplayed() can be used for existing element only. It returns false only if the element is found but is not displayed (hidden=true f.e.).
To check if element exists you can use List<WebElement> elements = driver.findElements(...); In case no element is found, you'll get empty List instead of NoSuchElementException.

Selenium click function is not getting Fail

The below code is written for click function.
public void click(By element) {
try {
driver.findElement(element).click();
}
catch (AssertionError e) {
System.out.println("Element " + element + " not found on page");
return;
}
}
The below code is written for calling the click function in my test case.
#Test(priority = 1)
public void accept_cookies_dialog() throws Exception {
try {
click(By.id(propObjctRepo.getProperty("id_cookieCta")));
} catch (Exception e) {
addErrorlogs(e, "Not found accpet cookie dialog.");
}
}
My concern is, In every case either the element present or not the test case is getting pass. I am doing something wrong, Please suggest me the solution.
Instead of using try/catch block, you can directly use assertions to check if the element is present on the page or not. If the list size of the element is greater than zero then the element is present on the page else it is not. By this, if the element is not present on the page, assertion will fail and so will the test case.
You can do it like:
Assert.assertTrue(driver.findElements(By.id(propObjctRepo.getProperty("id_cookieCta"))).size()>0);
And then below this you can click the element, so if and only if the assertion passes, your code will reach the click method else your test case will fail.

Selenium- exception instead of boolean value

I write a code where I have found the result element visible or not, but I have received an exception.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']"}
Here is my code
wd.navigate().refresh();
Thread.sleep(7000);
boolean airbnb = wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed();
assertFalse(airbnb, "Airbnb Add will not show After clicking Add one times");
Is there any suggestion why element not found showing? if element not found then it should be false I am not sure where I mistake?
To avoid an exception, and expensive use of try - catch, you can locate the element using findElements. If the result list is not empty you can check if the existed element is displayed or not
List<WebElement> elements = wd.findElements(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']"));
assertFalse(elements.size() > 0 && elements.get(0).isDisplayed(), "Airbnb Add will not show After clicking Add one times");
Either use try- catch block or use throws Exception to catch the NoSuchElementException
public void methodName() throws Exception
{
if(wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
{
System.out.println("Element displayed");
}
}
or
try
{
if(wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
{
System.out.println("Element displayed");
}
}
catch(NoSuchElementException e)
{
System.out.println("Element is not displayed");
}
Since you do not expect the element to be there the following code would throw an exception :
boolean airbnb = wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed();
and your assert statement would not even be reached.
You can actually place an expected exception in your code instead of asserting as(in Junit):
#Test(expected = NoSuchElementException.class)
public void youtTest() {
// do whatever you're doing
Thread.sleep(7000);
wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']"));
}
in TestNG the syntax is somehwat like :
#Test(expectedExceptions = { NoSuchElementException.class })
This is the issue with Selenium, you need to use try catch block something like below
try
{
if(wd.findElement(By.xpath(".//*[#class='airbnb-wide-block-search-btn js-airbnb-search-btn']")).isDisplayed())
{
//Your code
}
}
catch (Exception e)
{
//Your code
}
Let me put it this way: IsDisplayed will work on Object of Type WebElement.
here is the clarification
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
found on findElement

Checking for `driver.findElement(...)` in an IF statement throws `NoSuchElementException`

I'm getting NoSuchElementException when running the following code.
if (driver.findElement(By.xpath("//*[#id='gr2']")).isDisplayed()) {
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id='balInqTableStep2']/td/table/tbody/tr/td/table/tbody/tr[3]/td[4]/input[2]")).click();
}
else {
test.log(LogStatus.FAIL,"Please configure Gift Slabs for this site. Contact business.");
test.log(LogStatus.FAIL,"Second time wallet credit is not done");
}
NoSuchElementException exception means there is not element present on the page.
isDisplayed method assumes that element is already present on the page and so throws you exception when element is not present.
you can either make sure that element is present before calling webdriver method and you can write your own method to handle this for you.
following code snippet might help you
public boolean isDisplayed(By identifier){
boolean isElementDisplayed = false;
try{
WebElement element = driver.findElement(identifier);
isElementDisplayed = element.isDisplayed()
}catch (NoSuchElementException){
return false;
}
return isElementDisplayed;
}
and you can call it like this
isDisplayed(By.xpath("//*[#id='gr2']")
Always when you call driver.findElement(By.xpath("//*[#id='gr2']")) and the element is not present in the DOM, it's gonna throw a NoSuchElementException.
There is an alternative to avoid the code throwing the exception, calling the method findElements, instead of findElement.
E.g.:
List<WebElement> elements = driver.findElements(By.xpath("//*[#id='gr2']"));
if(!elements.isEmpty() && elements.get(0).isDisplayed()) {
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id='balInqTableStep2']/td/table/tbody/tr/td/table/tbody/tr[3]/td[4]/input[2]")).click();
}
else {
test.log(LogStatus.FAIL,"Please configure Gift Slabs for this site. Contact business.");
test.log(LogStatus.FAIL,"Second time wallet credit is not done");
}
Hope it works for you.

Which is the correct way to check if an element is present or displayed on a page with Selenium WebDriver using Java?

I'm testing a web application using Selenium WebDriver and I was wondering which is the proper method to check if the elements are present or displayed. I usually assert that all elements are present on the page but it also checks the hidden elements which in this case would also be necessary to check if the elements are displayed only when some action is done. For example I click a link and other fields and labels are displayed, while they were hidden before. In this case I should both check if the elements are present and also if they are or not displayed before and after some other element is clicked.
I was wondering which is the proper way to do this. Is it too much to check all the elements on the page ( assuming that I have some buttons, text-fields, labels, links etc. in the page)?
For the purpose of discussion I want to include some code snippets. To check that elements are present on the page I use the following snippet:
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
To check if an element is displayed I use the following snippet:
public boolean isElementDisplay(By by) {
if (driver.findElement(by).isDisplayed()) {
return true;
} else
return false;
}
One purpose of testing this application is to check if the elements exists and are displayed correctly. Am I doing the right thing here? Please give me your point of view. I've recently started working with Selenium WebDriver and being the only one in my company who does this...I don't have anyone to turn to. Any answer is appreciated.
There are no problems with it, except if you call your "checkIfDisplayed" method on an element that doesn't exist in the first place, it will throw an exception. I would modify it to this:
public boolean checkIfDisplayed(By by) {
if (isElementPresent(by) {
if (driver.findElement(by).isDisplayed()) {
return true;
} else
return false;
} else
return false;
}
(This may not be code that compiles, I am a C# man, but you should see what I mean)
It may have a slight performance hit, but overall what you are doing is perfectly fine anyway.
To check for element's existence I'd rather use
public boolean isElementPresent(By by)
{
return driver.findElements(by).size() > 0
}
I don't really get the idea behind your checkIfDisplayed function. It returns the result returned by WebElemet's isDisplayed() method without adding any new functionality...
EDIT
So far Arran provided the best answer. Just to modify it a little bit:
public boolean checkIfDisplayed(By by)
{
List<WebElemet> elements = driver.findElements(by);
return ((elements.size() > 0) && (elements[0].isDisplayed()));
}
I believe however that it would be better to call isElementPresent and isDisplayed separately. In this way you will know why the test failed (if it was caused by element's existence or visibility)
I use the same approach (I mean the same methods). But it is important to understand two things.
Some element can be present but not visible.
So for the purpose to verify whether element is present we can call the method
public boolean isElementPresent(By locatorKey) {
try {
driver.findElement(locatorKey);
return true;
} catch (NoSuchElementException e) {
return false;
}
But the drawback of isElementPresent method it can point out elements in DOM model that are not visible on the page and consequently are not accesssible with webDriver. So in that case additional check helps us:
driver.findElement(By.xpath(....)).isDisplayed()
Hope things come clear now)
I'd say your first method looks just fine.
The 2nd thus will give you trouble if the findElement-call will give you no result.
You should add a check if there is an element found and then check if it's displayed:
try {
final WebElement elem = driver.findElement(by);
elem.isDisplayed();
return true;
} catch (NoSuchElementException nse) {
return false;
}
Also note: You are ignore the possibility that more than one element matches the criteria given by the by instance. See the findElemts() method.
You can also combine both the methods as per your requirement as follows,
if(driver.findElements(By.LOCATOR).size()>0)
{
if(driver.findElement(By.LOCATOR).isDisplayed())
{ print "Element is present and displayed"; }
else
{ print "Element is present but not displayed"; }
}
else
{ print "Element is not present"; }

Categories