1

I have several inherited classes that all have similar web elements. It is just that in each sub class, the actual xpath of the elements is different. All the interactions I want to do are the same among all the subclasses, except for the xpath.

I want to do something like

@FindBy(xpath = *somehow passed in constructor from subclass*)
private WebElement searchBox;

in the superclass. Then I can have my methods which act on the elements passed into it. I don't think I can pass the element from the subclass because the element will be dynamic, and this will be done statically (or just one time, and the element could change).

I can't define the xpaths in the super class as the xpaths are different in each subclass.

I would appreciate any suggestions. I suppose I could pass the strings and do my own finds if necessary (driver.findElement(By.xpath(...))

Oh, this is to be done with Java and Eclipse

Tony
  • 1,127
  • 1
  • 18
  • 29

2 Answers2

0

Should point out that since your WebElement instance is private, then I don't think subclassed page objects will have access to those instances of webelement. If your WebElement was 'protected', then you could access it from subclass and if you declared a new variable in the subclass of the same name, then the new one would override the one in the parent class AFAIK.

Also, you cant pass the elements in the constructor like you are implying: instead, load them in the subclass using PageFactory.initObjects(parentClass), or something like that. The annotations can't take variables as arguments, AFAIK.

class HomePage extends ParentPage {
  public HomePage() {
    ParentPage pp = PageFactory.initElements(driver, ParentPage.class);
    HomePage hp = PageFactory.initElements(driver, this);
    ....

Never tried that before, but I would assume it might work.

djangofan
  • 28,471
  • 61
  • 196
  • 289
  • I am trying to understand it, and then I will try it when I have an understanding of what those do. Guess I am still a bit of a neophyte ;-) – Tony Mar 22 '16 at 19:41
0

You might try a template method pattern where your superclass as an abstract class, which defines abstract methods to return selectors for your WebElements. The child classes would include the class-specific @FindBy() definitions of your WebElements. (I don't know that this will work...just an idea.)

public abstract class MySuperClass {
    public abstract By getFooSelector(); 
    public void someMethodThatUsesFoo() {
        WebElement foo = driver.findElement(getFooSelector());
        ...
    }
}

public class MySubClass extends MySuperClass {
    public By getFooSelector() {
        return new By.ByXpath("foo/X/path");
    }
}
Breaks Software
  • 1,721
  • 1
  • 10
  • 15