2

Is it possible to use @FindBy not only with WebElement, but with my own class?

I would like to have my class for cooperating with page elements and to override some methods of WebElement interface in it.

So that I implemented the class:

public class NamedElement implements WebElement {
    public boolean isDisplayed(){
        try{
            return element.isDisplayed();
        } catch (NoSuchElementException noElement) {
            return false;
        }
    }

And would like to declare the element like this:

@FindBy(xpath = ".//a[contains(text(), 'Log in')]")
public NamedElement loginButton;

But I get the error:

java.lang.IllegalArgumentException: Can not set lenovo.tests.page.NamedElement field lenovo.tests.page.NCBLoginPage.loginButton to com.sun.proxy.$Proxy9
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at org.openqa.selenium.support.PageFactory.proxyFields(PageFactory.java:116)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:104)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:91)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:78)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:64)
at lenovo.tests.step.NCBLoginStep.<init>(NCBLoginStep.java:20)

Could you please advice me the proper way to override WebElement methods and to use my .isDispalyed() method instead? I would like to continue using the @FindBy annotation.

BohdanN
  • 599
  • 10
  • 33

1 Answers1

3

This answer here is describing what you want. He documented the way to create your own PageFactory in this blog - which is the way to go. At least we (at work) are doing exactly that. Our goal is to have an automatic retry on every WebElement method instead of nasty StaleElementReferenceExceptions and scroll an element automatically into view, if Chrome cannot handle it on its own. ;-)

Community
  • 1
  • 1
Carsten
  • 1,919
  • 1
  • 15
  • 40