Passing WebElement as parameter to implicit wait method - java

I wrote the below method in my Page.class for reusing implicit wait.
public WebDriver waitForElementToLoad(WebElement element)
{
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
return (driver);
}
In my test.class I am using page factory elements, for example:
//Save button
#FindBy(xpath = "//*[#*='Save']")
private WebElement saveButton;
Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.
"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
org.openqa.selenium.By are in unnamed module of loader 'app')"
I also tried
WebElement saveButton = driver.findElement(By.xpath("//*[#*='Save']"));
waitForElementToLoad(saveButton);
but no luck.
How can I make this work?

WebDriverWait is explicit wait, not implicit. And you can't cast WebElement to By.
If saveButton is not null than it was already found by the page factory, waiting for it presence is meaningless, that's why you don't have an overload with WebElement. Wait for visibility instead
wait.until(ExpectedConditions.visibilityOf(element));

If you need to use ExpectedConditions with some your "Page" class that contains asynchronously loaded elements I would recommend to use the following approach:
Extend AjaxElementLocator where override protected boolean isElementUsable(WebElement element) so that it uses ExpectedConditions to decide if the element is ready for use
Extend AjaxElementLocatorFactory where override public ElementLocator createLocator(Field field) method so that it now returns the instance of your extended class
Where you initialize elements use PageFactory.initElements(new MyAjaxElementLocatorFactory(driver, 10), this); where MyAjaxElementLocatorFactory is the class that you created on step 2

This error message...
java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and org.openqa.selenium.By are in unnamed module of loader 'app')
...implies that the ClassCastException occured while trying to cast a proxy object.
You need to consider a few things as follows:
The wait you introduced within waitForElementToLoad() isn't implicit wait as such but an ExplicitWait. See: What is the internal working difference between Implicit Wait and Explicit Wait
presenceOfElementLocated() doesn't garuntees the visibility or interactablity of any element. So for visibility or interactablity you need to use the matching ExpectedConditions either visibilityOf(WebElement element) or elementToBeClickable(By locator). For details, see: Selenium: How selenium identifies elements visible or not? Is is possible that it is loaded in DOM but not rendered on UI?
If your usecase involves inducing WebDriverWait you pass the WebElement saveButton in the form of a proxy object within waitForElementToLoad() as follows:
package com.pol.zoho.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//Save button
#FindBy(xpath = "//*[#*='Save']")
private WebElement saveButton;
public void waitForElementToLoad()
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
saveButton.click();
}
public WebElement getWebElement()
{
return saveButton;
}
}
Reference
You can find a couple of relevant discussions in:
How to add explicit wait in PageFactory in PageObjectModel?
How to wait for invisibility of an element through PageFactory using Selenium and Java

Related

Wait until element doesn't exists using PageFactory

I'm trying to use only PageFactory in my project, without using fields with type By. And I'm looking to implement something like this:
#FindBy(className = "loading-container")
private WebElement loadingElement;
public LoadingPage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.waitDriver = new WebDriverWait(this.driver, 20);
}
public void waitLoadingToFinish() {
this.waitDriver.until(ExpectedConditions.elementNotExists(loadingElement));
}
Is there a way to implemet custom Expected Condition for this? or any other way to implement this? (without using By fields, only using page factory).
As far as I understand you have some elements on the page that you consider ready for usage only when there is no certain element on the page (like waiting wheel).
There is a special locator class in Selenium called AjaxElementLocator. What you need to do is to extend that type by changing isElementUsable method when you initialize your page so that all the controls you use on that page would first check the condition. Here is the example:
package click.webelement.pagefactory.conditions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocator;
public class LoadablePage {
#FindBy(id = "cntrl-id")
WebElement control;
public LoadablePage(WebDriver driver){
PageFactory.initElements(field -> new AjaxElementLocator(driver, field, 10){
#Override
protected boolean isElementUsable(WebElement element) {
return driver.findElements(By.xpath("//WHEEL_XPATH")).size() == 0;
}
}, this);
}
}
Here you can find more information on such approach.
Selenium has this method
ExpectedConditions.InvisibilityOfElementLocated
An expectation for checking that an element is either invisible or not
present on the DOM.
For your code
public void waitLoadingToFinish() {
this.waitDriver.until(ExpectedConditions.invisibilityOfElementLocated(loadingElement));
}
also, you might try to add a javascript executor to wait until the page is loaded
public static void waitForScriptsToLoad(WebDriver driver) {
WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd ->
((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
}
and then your page constructor becomes this
public LoadingPage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.waitDriver = new WebDriverWait(this.driver, 20);
waitForScriptsToLoad(driver);
}
If you create wait method in your program that is easy and customize in selenium framework
private static WebElement waitForElement(By locator, int timeout)
{
WebElement element=new WebDriverWait(driver,timeout).until(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
//If you want wait for id following code should use
waitForElement(By.id(""),20);
Here 20 is miliseconds
and you can use any web elements to wait
To simulate an ExpectedConditions like elementNotExists you can use either among invisibilityOfElementLocated() or invisibilityOf().
invisibilityOfElementLocated()
invisibilityOfElementLocated() is the implementation for an expectation for checking that an element is either invisible or not present on the DOM. It is defined as follows:
public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementLocated(By locator)
An expectation for checking that an element is either invisible or not present on the DOM.
Parameters:
locator - used to find the element
Returns:
true if the element is not displayed or the element doesn't exist or stale element
Code Block:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class fooPage {
WebDriver driver;
public fooPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//you don't need this
//#FindBy(className = "loading-container")
//private WebElement loadingElement;
public void foo()
{
Boolean bool = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.className('loading-container')));
//other lines of code
}
}
As an alternative you can also use the invisibilityOf() method as follows:
invisibilityOf()
invisibilityOf() is the implementation for an expectation for checking the element to be invisible. It is defined as follows:
public static ExpectedCondition<java.lang.Boolean> invisibilityOf(WebElement element)
An expectation for checking the element to be invisible
Parameters:
element - used to check its invisibility
Returns:
Boolean true when elements is not visible anymore
Code Block:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class fooPage {
WebDriver driver;
public fooPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(className= 'loading-container')
WebElement loadingElement;
public void foo()
{
Boolean bool = new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOf(fooPage.getWebElement()));
//other lines of code
}
public WebElement getWebElement()
{
return loadingElement;
}
}
You can find a detailed discussion in How to use explicit waits with PageFactory fields and the PageObject pattern

Can I make the WebDrivers as global variables in Java

I want to create a class where I set all the common actions of the WebDrivers such as: waitExplicit, findElement, click. But if I create a method then I have to create the WebDriver and WebDriverWait over and over on each method of the class, I already tried having a class for the Drivers, but when I call the methods, they just create instances over and over, so multiple windows open, I tried this way, but still cannot get to it:
public class AutomationActions{
static LoadProperties prop = new LoadProperties(); //This class has the System.setProperty for the driver
prop.getSysProp(); //***This is the issue, how can I solve this?****
WebDriver driver = new ChromeDriver(); //this will not work without the one above working
WebDriverWait wait = new WebDriverWait(driver, 30);//this will not work without the one above working
public void waitForPageToLoad() throws Exception {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
// WebDriverWait wait = new WebDriverWait(driver, 30); // I want to avoid having to set this in every method
wait.until(pageLoadCondition); //this is supposed to replace the line of code above
}
I don't really work on Java much any more, I've written our framework in C# but I put together some quick classes in Java to show you how I set things up. I use page object model and I recommend you do too so I've written this example using page object model. I've written a simple test that uses Dave Haeffner's (one of the Selenium contributors) demo site, http://the-internet.herokuapp.com.
The basic concepts are:
There is a class BaseTest that holds things that correspond to tests, e.g. setting up the driver at the start of the test, quitting the driver at the end of the test, etc. All of your tests will inherit from BaseTest
There is a class BasePage that holds things that correspond to generic methods for finding elements, clicking on elements, etc. Each of your tests inherit from BasePage. (This is what I think the main part of your question is asking about).
To follow the page object model, each page (or part of a page) is its own class and holds all locators and actions done on that page. For example, a simple login page would have the locators for username, password, and the login button. It would also hold a method Login() that takes a String username and a String password, enters those in the appropriate fields and clicks the Login button.
The final class of this example is a sample test aptly named SampleTest.
You shouldn't have any FindElements() or related calls in your tests, all those should be in the appropriate page object.
This is using TestNG as the unit test library. Use it or JUnit, your preference but if you use JUnit, you will need to change the asserts and the annotations.
Under 'src', I create a folder for page objects, 'PageObjects', and a folder for tests, 'Tests'. Here's what the files look like on disk.
\src
\PageObjects
BasePage.java
DropdownListPage.java
\Tests
BaseTest.java
SampleTest.java
BasePage.java
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class BasePage
{
private WebDriver driver;
private final int shortWait = 10;
public BasePage(WebDriver _driver)
{
driver = _driver;
}
public void ClickElement(By locator)
{
new WebDriverWait(driver, shortWait).until(ExpectedConditions.elementToBeClickable(locator)).click();
}
public WebElement FindElement(By locator)
{
return new WebDriverWait(driver, shortWait).until(ExpectedConditions.presenceOfElementLocated(locator));
}
// add more methods
}
DropdownListPage.java
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownListPage extends BasePage
{
private final By dropdownListLocator = By.id("dropdown");
public DropdownListPage(WebDriver _driver)
{
super(_driver);
}
public String GetSelectedOption()
{
return new Select(FindElement(dropdownListLocator)).getFirstSelectedOption().getText();
}
public void SelectOptionByIndex(int index)
{
new Select(FindElement(dropdownListLocator)).selectByIndex(index);
}
}
BaseTest.java
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class BaseTest
{
public WebDriver driver;
public WebDriver GetChromeDriver()
{
System.setProperty("webdriver.chrome.driver", "C:\\Path\\To\\Chrome\\Driver\\chromedriver.exe");
return new ChromeDriver();
}
#BeforeTest
public void Setup()
{
driver = GetChromeDriver();
driver.manage().window().maximize();
driver.get("http://the-internet.herokuapp.com/dropdown");
}
#AfterTest
public void Teardown()
{
driver.close();
}
}
SampleTest.java
package Tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import PageObjects.DropdownListPage;
public class SampleTest extends BaseTest
{
#Test
public void SampleTestCase()
{
DropdownListPage dropdownListPage = new DropdownListPage(driver);
dropdownListPage.SelectOptionByIndex(1);
Assert.assertEquals(dropdownListPage.GetSelectedOption(), "Option 1", "Verify first option was selected");
}
}
You will need to create a project that contains Selenium for Java and TestNG. Download them and put them on your build path. Create the folder structure as described above and create each of these classes and copy/paste the contents into them. Now all you need to do is run SampleTest as a TestNG Test and it should go.
The test creates a new Chromedriver instance, navigates to the sample page, selects the first option in the dropdown, asserts that the dropdown text is correct, and then quits the driver.
That should get you started. There's a lot of info crammed into the above wall of text, let me know if you have some questions.

Use visibilityOfElementLocated with pagefactory

I'm writing automated scripts using page factory and I want to use visibilityOfElementLocated with page factory instead of visibilityOf
I tried to use visibilityOf but some times it not work with my element
the problem here that visibilityOfElementLocated take By parameter, and I have WebElment
#FindBy(id = "test")
WebElement locator;
You can't use it directly with #FindBy, but you can call it from a method that will run before PageFactory.initElements
public abstract class BasePage {
protected WebDriverWait wait;
public BasePage(WebDriver driver) {
wait = new WebDriverWait(driver, 10);
assertInPage();
PageFactory.initElements(driver, this);
}
public abstract void assertInPage();
}
public class DerivedPage extends BasePage {
#FindBy(id = "test")
WebElement locator;
public DerivedPage(WebDriver driver) {
super(driver);
}
#Override
public void assertInPage() {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("test")));
}
}
assertInPage() in DerivedPage will be executed right before PageFactory.initElements.
visibilityOfElementLocated(By locator)
visibilityOfElementLocated(By locator) takes a __By locator_ as an argument and is the expectation for checking that an element is present on the DOM of a page and visible.
visibilityOf(WebElement element)
visibilityOf(WebElement element) takes an WebElement as an argument and is the expectation for checking that an element, known to be present on the DOM of a page, is visible.
When using PageFactory in PageObjectModel if you expect the element to be dynamic and loaded through some JavaScript and might not be present on the page already you can use the Explicit Wait support with a normal locator factory as follows:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestPage {
WebDriver driver;
//constructor
public TestPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
//Locator Strategy
#FindBy(id = "test")
WebElement locator;
//Test Method
public void testMethod()
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOf(TestPage.getWebElement()));
//perform your desired action here e.g element.click()
}
public WebElement getWebElement()
{
return locator;
}
}
You can find a detailed discussion in How to add explicit wait in PageFactory in PageObjectModel?

Mapping dynamic elements with #FindBy annotations and PageFactory

For the Page Object example class below, I have an accountsLink private member which maps to a non-dynamic element on the Login page when it loads. It is initialized using the FindBy annotation when the initElements method is called from the constructor.
public class Login {
private WebDriver driver;
#FindBy(id = "account")
private WebElement accountsLink;
//constructor, elements are initialized by the PageFactory
public MainPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
//clicking accounts opens a dynamic ajax menu which has a Sign In Button
public SignInPage clickAccountsLink() {
accountsLink.click();
WebElement signInButton = driver.findElement(By.id("signin"));
signInButton.click();
return new SignInPage(driver);
}
}
Now for the problem. I have another element (signInButton) which is dynamically loaded only when you click the accountsLink element. This action doesn't take you to another page but only brings up an ajax menu where the sign in button will appear.
My question is, since the signInButton element only appears when the accountsLink element is clicked, can it be declared as a member of the Login class with a FindBy annotation or do I have to stick with my current solution of using a driver.findElement(By.id("signin")) inside the clickAccountsLink method?
I hope my question makes sense.
When PageFactory.initElements is called it parses the current DOM. If the WebElement doesn't exist in that time it can't be given as a value to a variable, exactly as you can't locate non-existing WebElement using driver.findElement.
Your solution is the way to go, although I would use explicit wait and Expected Conditions when loading the signInButton.
You can declare, I don't think it's gonna give you any error. Page Factory creates a dummy element when it initialized the class. It creates the actual element only when you intersect with the element for the first time.
For example in following class NoExistingElement element doesn't exist and it won't give me any error, If I will call the enterText method of class. The test case will pass without any error.
However, If i will try to call any function on NoExistingElement element then only it will fail with Webdriver exception, ElementNotFoundException
public class GoogleSearch {
#FindBy(name="q")
static WebElement searchBox;
#FindBy(name = "qqqqq")
WebElement NoExistingElement;
public GoogleSearch(WebDriver driver){
PageFactory.initElements(driver, this);
driver.get("https://www.google.com");
}
public void searchOnGoogle(String text){
searchBox.sendKeys(text);
}
}

Selenium utility to wait for an Element

I am new to the selenium framework and writing a method for the presence of element. Below is the method which I wrote:
public class WebUtlities {
WebDriver driver;
public void waitforanelement(WebElement element)
{
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
}
When I call this method for an element, I see the below error:
java.lang.ClassCastException: com.sun.proxy.$Proxy6 cannot be cast to org.openqa.selenium.By
at Uilities.WebUtlities.waitforanelement(WebUtlities.java:16)
at TestScripts.Testcases.Selfpay(Testcases.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Please correct me how to make it work for the element to wait
Try with this
public class WebUtlities {
WebDriver driver;
public void waitforanelement(WebElement element)
{
driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("xpath of that element"))); //you can use any other By like id, cssselector, name, linktext etc
}
Hope this helps
use the below code:
public void waitforanelement(By element)
{
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.presenceOfElementLocated(element));
}
when u call the method, do like below:
By css = By.cssSelector("ur selector");
waitforanelement(css);
hope this will help u.
The problem lies with this line:
wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
Firstly, the presenceOfElementLocated method is used to locate an element on the page, rather than to check that a previously found element is present on the page - as such you should change the argument for your waitforanelement method to accept a By locator instead of a WebElement like so:
public void waitforanelement(By by)
You should then subsequently change the arguments passed to the presenceOfElementLocated method like so:
wait.until(ExpectedConditions.presenceOfElementLocated(by));
The Javadoc for the By class lists the locators you can use.
The problem as you can see from the error is that
new WebDriverWait(driver,20);
wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
returns an WebElement instance which should be assigned to an WebElement. So It can not cast a WebElement to nothing.
Follow the following list for complete list of methods of ExpectedConditions Class.
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html
Try the following,
public WebElement waitforanelement(WebElement element)
{
WebDriverWait wait= new WebDriverWait(driver,20);
WebElement Element=wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
return Element1;
}

Categories