try catch until success java - java

I get Stale Element Reference Exception.If I can single click.
I want to click on element until or 5 times find the object.
How can I have try catch block loop until click or element found?
I want it to attempt to click on element for 5 times before failing it.
I use below code but not working.
Click Method:
public void click1(WebDriver driver, WebElement element, String name) {
int attempts = 0;
while(attempts < 5) {
try {
element.click();
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
break;
} catch (Exception e) {
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
break;
} catch (Exception e2) {
Add_Log.info("Not able to click " + name);
Reporter.log("Not able to click " + name);
TestResultStatus.Testfail = true;
Assert.fail();
}
}
attempts++;
}
}

This is actually as easy as changing the loop condition from attempts < 5 to true and removing the attempts++; line. At least that's what I understood from your question. If that's not what you're looking for, try rephrasing the question more clearly.

I would write it more like the below. You attempt to do a normal click 5 times with a brief pause between attempts. If an exception is thrown, it's eaten and another attempt is made. If none of those 5 are successful, you make a single attempt to click on it using JS. If that fails, then log failures, etc.
public void click1(WebDriver driver, WebElement element, String name) {
int attempts = 0;
while(attempts < 5) {
try {
element.click();
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e) {
}
attempts++;
Thread.Sleep(500); // brief pause between attempts
}
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e2) {
Add_Log.info("Not able to click " + name);
Reporter.log("Not able to click " + name);
TestResultStatus.Testfail = true;
Assert.fail("Not able to click " + name);
}
}
NOTE: You probably would be better off waiting for the element to be clickable before attempting to click it. That would probably remedy most of your issues. You still may have an issue with some dialog/banner/spinner overlapping the element that you would need to deal with though... and you could deal with that with the 5 attempted clicks, etc.

Related

Actions.click() throws StaleElementReferenceException, but WebElement.click() does not

In my test project, I have a static class that contains a number of methods for basic interactions with WebElements. I have two separate methods for clicking a WebElement, one that uses the WebElement.click() method:
public static void click(WebElement element, WebDriverWait w) {
if (element == null) {
return;
}
try {
w.until(ExpectedConditions.elementToBeClickable(element)).click();
} catch (TimeoutException ex) {
Assert.fail("Test failed, because element with locator: " + element.toString().split("->")[1] + " was not found on the page or unavailable");
}
}
and one that uses the Actions.click(WebElement).build().perform() method:
public static void click(WebElement element, Actions a, WebDriverWait w) {
if (element == null) {
return;
}
try {
a.click(w.until(ExpectedConditions.elementToBeClickable(element))).build().perform();
} catch (TimeoutException ex) {
Assert.fail("Test failed, because element with locator: " + element.toString().split("->")[1] + " was not found on the page or unavailable");
}
}
I also have a method for finding and then clicking an option from a menu:
public void selectItem(IMenuButton button) {
for (WebElement item : w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("*[role='menuitem']")))) {
if (item.findElement(By.tagName("span")).getText().trim().equalsIgnoreCase(button.getButton())) {
// This throws StaleElementReferenceException
Interaction.click(item, a, w);
// This works
Interaction.click(item, w);
return;
}
}
Assert.fail("No menu item found for: " + button.getButton());
}
When I use Interaction.click(item, w), it works, but Interaction.click(item, a, w) throws StaleElementReferenceException, and I can't figure out why. I need the method that uses Actions.click() in case the option needs to be scrolled into view. Any ideas?
Selenium 4
Chromedriver 99
Java
Usually, when you scroll down or up - the DOM changes. StaleElementReferenceException means that an element you once found has been moved or deleted. When going over elements inside a loop, very often elements inside a dropdown or scrollView, you need to find them all over again. Otherwise you will get this exception over and over again.
Try to do this:
try {
Interaction.click(item, a, w);
} catch (StaleElementReferenceException sere) {
// re-find the item by ID, Xpath or Css
item = driver.findElementByID("TheID");
//click again on the element
Interaction.click(item, a, w);
}

Implement a global listener for Selenium tests

I use this code to click on a series of dialog windows with unique button ID. It was working fine till now because the order was strict:
clickConfirmWindow(driver, SURVEY_EXIT_BUTTON_ID_LOCATOR, "Survey exit window");
... and many mode windows with unique ID with random order
protected void clickConfirmWindow(WebDriver driver, String elementId, String name) {
// Check if warning window is displayed using button ID
System.out.println("Searching " + name + " using " + elementId);
if (isClickable(driver, elementId, 1)) {
System.out.println("Found " + name + " using " + elementId);
driver.findElement(By.id(elementId)).click();
}
}
protected void clickConfirmWindow(WebDriver driver, String elementId, String name) {
// Check if warning window is displayed using button ID
System.out.println("Searching " + name + " using " + elementId);
if (isClickable(driver, elementId, 1)) {
System.out.println("Found " + name + " using " + elementId);
driver.findElement(By.id(elementId)).click();
}
}
private Boolean isClickable(WebDriver driver, String elementId, int timeOut) {
try {
new WebDriverWait(driver, timeOut).until(ExpectedConditions.visibilityOfElementLocated(By.id(elementId)));
return true;
} catch (TimeoutException e) {
e.printStackTrace();
return false;
}
}
But now the order of the windows is random. Is it possible to implement some kind of global listener which listens for web element ID thru out the entire application and clicks it if it's present?
not sure about your specific situation but in vba I would write an if statement to see if it was true,
If driver.findelementsbyid("your Id").count > 0 then
driver.findelementbyid("your Id").click
Else
End if
Searching if the element exists should help you
WebElement elementName = driver.findElement(By.id("idElement"));
if(elementName != null){
//Loaded Element
}

Appium is able to see beyond what is displayed on screen

Appium is able to see and find elements that is not displayed on screen
I am trying to build a test automation project, I would like my driver to scroll down
and then perform some operation. but for some reason appium is able to find element even without scrolling down . I am not sure how appium is able to identify element that is not on screen and is only visible to naked eye when you scroll down. Anyone with similar issue found a workaround ?
I am using ExpectedCondition.visibilityOF(element) to determine if element is vsible on screen
public boolean verifyCoverage(String coverage, String value, String type) throws IOException, InterruptedException {
int counter = 0;
for (int i = 0; i < 15; i++) {
AndroidElement element = (AndroidElement) driver.findElementByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")");
//WebElement coverageOption= driver.findElementByXPath("//android.widget.Button[contains(text(),'"+coverage+"')]");
if (AndroidUtilities.waitForVisibility(driver, element)) {
return true;
}
else {
System.out.println ("Cannot see");
return false;
}
}
public static boolean waitForVisibility(AndroidDriver<WebElement> driver, AndroidElement AndroidElement){
try{
// driver.findElementByAndroidUIAutomator("UiSelector().resourceId(\""+targetResourceId+"\")");
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(AndroidElement));
boolean isElementPresent = AndroidElement.isDisplayed();
return isElementPresent;
}catch(Exception e){
boolean isElementPresent = false;
System.out.println(e.getMessage());
return isElementPresent;
}
}
As an answer i would recommend you to use visibilityOfElementLocated instean of visibilityOf.
Plus, if you want to check an element for the existence without getting exceptions, try to take that approach:
if (!((AndroidDriver)driver).findElementsByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")").isEmpty()) {
//some logic when element is located
} else {
//scroll to the particular element
}
You can try these two solution within the page it will able to scroll to the element and do your actions .
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""+element+"\").instance(0))"));
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textMatches(\"" + NumbersCount + "\").instance(0))"));

Selenium - Determine whether web page is finished loading in Angular 2+

I have a Selenium test suite that is running Selenium integration tests against a number of web applications, some that are written in Angular 2+, and some that are written in AngularJS.
We use a custom ExpectedCondition with WebDriverWait that we use to make test cases wait until AngularJS apps have finished loading, in order to avoid waiting an arbitrary amount of time:
private static ExpectedCondition<Boolean> angularIsFinished() {
return new ExpectedCondition<Boolean>() {
public Boolean apply(final WebDriver driver) {
Object result = null;
while(result == null || result.toString().equals("undefined")) {
result = ((JavascriptExecutor)driver).executeScript("return typeof angular;");
try {
Thread.sleep(200L);
} catch (final InterruptedException ex) {
logger.error("Error while trying to sleep", ex);
}
}
final String script = " var el = document.querySelector(\"body\");\n" +
" var callback = arguments[arguments.length - 1];\n" +
" angular.element(el).injector().get('$browser').notifyWhenNoOutstandingRequests(callback);";
((JavascriptExecutor)driver).executeAsyncScript(script);
return true;
}
public String toString() {
return "Wait for AngularJS";
}
};
}
However, return typeof angular; will always return undefined for an Angular 2+ app. Is there a similar way to AngularJS's notifyWhenNoOutstandingRequests that you can use to determine when an Angular 2+ app has finished loading?
This question mentions using NgZone as a possible solution, but how would you get a handle on that via a script executed via JavascriptExecutor?
You can check it by calling e.g. document.querySelector('app-root')? or arbitrary component selector...
Or what about calling document.readyState? It should have result 'complete' after fully loaded wep page and it doesn't matter if web page is based on angular.
Thanks to #Ardesco's answer, I was able to do something similar to what Protractor does, using the window.getAllAngularTestabilities function. Here is the script that I run to determine if the Angular 2+ page loads:
var testability = window.getAllAngularTestabilities()[0];
var callback = arguments[arguments.length - 1];
testability.whenStable(callback);
And here is what the complete ExpectedCondition looks like that works for both AngularJS and Angular 2+:
private static ExpectedCondition<Boolean> angularIsFinished() {
return new ExpectedCondition<Boolean>() {
public Boolean apply(final WebDriver driver) {
Object result = null;
boolean isAngular2Plus = false;
while(result == null || result.toString().equals("undefined")) {
result = ((JavascriptExecutor)driver).executeScript("return typeof angular;");
if (result == null || result.toString().equals("undefined")) {
result = ((JavascriptExecutor)driver).executeScript("return typeof window.getAngularTestability;");
if (result != null && !result.toString().equals("undefined")) {
isAngular2Plus = true;
}
}
try {
Thread.sleep(200L);
} catch (final InterruptedException ex) {
logger.error("Error while trying to sleep", ex);
}
}
final String script;
if (isAngular2Plus) {
script =" var testability = window.getAllAngularTestabilities()[0];\n" +
" var callback = arguments[arguments.length - 1];\n" +
" testability.whenStable(callback);";
} else {
script =" var el = document.querySelector(\"body\");\n" +
" var callback = arguments[arguments.length - 1];\n" +
" angular.element(el).injector().get('$browser').notifyWhenNoOutstandingRequests(callback);";
}
((JavascriptExecutor) driver).executeAsyncScript(script);
return true;
}
public String toString() {
return "Wait for AngularJS";
}
};
}
Looking at the Protractor code I have come up with two possible solutions:
First of all we have an option where we find a list of testability's, then add a callback to all of them, and then wait for one of them to flag the site as testable (This does mean that your script will continue after any one testability has become testable, it will not wait for all of them to become testable).
private static ExpectedCondition angular2IsTestable() {
return (ExpectedCondition<Boolean>) driver -> {
JavascriptExecutor jsexec = ((JavascriptExecutor) driver);
Object result = jsexec.executeAsyncScript("window.seleniumCallback = arguments[arguments.length -1];\n" +
"if (window.getAllAngularTestabilities()) {\n" +
" window.getAllAngularTestabilities().forEach(function (testability) {\n" +
" testability.whenStable(window.seleniumCallback(true))\n" +
" }\n" +
" );\n" +
"} else {\n" +
" window.seleniumCallback(false)\n" +
"}"
);
return Boolean.parseBoolean(result.toString());
};
}
The second option is to specifically check an angular root elements testability state:
private static ExpectedCondition angular2ElementIsTestable(final WebElement element) {
return (ExpectedCondition<Boolean>) driver -> {
JavascriptExecutor jsexec = ((JavascriptExecutor) driver);
Object result = jsexec.executeAsyncScript(
"window.seleniumCallback = arguments[arguments.length -1];\n" +
"var element = arguments[0];\n" +
"if (window.getAngularTestability && window.getAngularTestability(element)) {\n" +
" window.getAngularTestability(element).whenStable(window.seleniumCallback(true));\n" +
"} else {\n" +
" window.seleniumCallback(false)\n" +
"}"
, element);
return Boolean.parseBoolean(result.toString());
};
}
The second option is more targeted and therefore more reliable if you want to test a specific area of the site.
A third option would be to write something a bit more complicated that tracks the state of all testability's and then only fires a true callback when all of them have become true. I don't have an implementation for this yet.

Code is getting into an infinite search when executed via TestNG

The below code is getting into an infinite search when running via TestNG, otherwise giving correct results when executed directly in Main method via Java Application.
Boolean iselementpresent = driver.findElements(By.linkText("Foreign exchange1")).size()!= 0;
Infinite search-->
public boolean checkLinkPresence(String linkName){
Boolean iselementpresent = driver.findElements(By.linkText("Foreign exchange1")).size()!= 0;
if (iselementpresent == true)
return true;
else{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
}
You should not be using main method in TestNG as everything works with annotations. However make sure your implicit wait time is short so that the command findElements timeouts after that. If you have not given an implicit wait, try giving one and then try running your method. Here's an example -
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //set this before you get the url using driver.get()
Once your implicit wait time is set, try running your method.
public boolean checkLinkPresence(String linkName){
List elements = driver.findElements(By.linkText("Foreign exchange1"));
if (elements.size() != 0)
return true;
else{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
}
Hope it helps.
This is how I would write this function...
public boolean checkLinkPresence(String linkName)
{
if (driver.findElements(By.linkText(linkName)).isEmpty())
{
System.out.print("Element " + linkName + " not Present");
APP_LOGS.debug("Element " + linkName + " not Present");
return false;
}
return true;
}
Your locator had a hard coded string in it By.linkText("Foreign exchange1"), so no matter what string you passed the function, it was always looking for that one string.

Categories

Resources