I am developing a selenium WebDriver framework [Java] in which there is a Base Class and every other class extends from this class. Also I am following Page Object Model where in each page corresponds to a class and method in which navigates to next page return new instance of the next page/class. In short each UI Page corresponds to Class
Now every page have some common functionality so instead of putting them in to each class and avoiding DRY I am putting this in my Base Page class
for ex goBack method is on every page which basically navigates to the previous page.
My concern is I want to follow chaining between the pages/classes and hence I am not sure what should be the return type of the common methods for ex goBack.
Remember any method which navigates to next page should return new instance of that page.
One solution I thought was to implement Generics but still struggling . Can any one help me as to how can I achieve this.
public class BasePage {
public WebDriver driver;
public BasePage(WebDriver driver) {
this.driver=driver;
}
public BasePage clickGoBack() throws Exception{
driver.click(goBackButton);
return this;
}
}
The easiest way is to learn concepts such as SOLID, DRY, FIT, DDD, TDD, MVC, etc. As you look up these acronyms it will lead you down many other rabbit holes and once you are done with your reading you should have a good understanding of what better object-oriented programming is!
OOP can also be used in manufacturing and design applications, as it allows people to reduce the effort involved. For instance, it can be used while designing blueprints and flowcharts. OOP makes it possible for the designers and engineers to produce these flowcharts and blueprints accurately.
BasePage
needs to know the implementing type for chaining:
/**
* @param <T> The implementing type.
*/
public abstract class BasePage<T extends BasePage<T>> {}
Then, you could use:
public T clickGoBack() { return (T) this; }
The problem here, is that this
isn't necessarily an instance of T
so the cast is not safe, for example with the following class:
public class Page1 extends BasePage<Page2> {}
A solution is to ask the subclasses their this
:
public abstract class BasePage<T extends BasePage<T>> {
protected final WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
}
public T clickGoBack() throws Exception{
driver.click(goBackButton);
return getThis();
}
protected abstract T getThis();
}
public class HomePage extends BasePage<HomePage> {
public HomePage(WebDriver driver) {
super(driver);
}
@Override
protected HomePage getThis() {
return this;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With