BaseTest, BasePage and the limits of inheritance
A base class holds only what every descendant needs: run setup in BaseTest, the driver and waits in BasePage. Inheritance means "is a kind of" and tightly couples a child to its parent, and a Java class has only one parent, so a base class bloats quickly. Shared UI parts such as a header or a table go into components held as fields, and lifecycle methods get unique names.
Java · OOP
BasePage already has 40 methods and every new page inherits them all. Where is the limit of inheritance?
A framework grows along a familiar path. First there is a BaseTest that starts the driver and a BasePage with waits. Then BasePage gets methods for tables, for modal windows, for file uploads, because "it is convenient: all pages have them". Half a year later LoginPage inherits a selectRow method it does not have and never will, and a change to one ancestor method breaks twenty pages.
This lesson covers what belongs in a base class, what to extract into separate components, and how this ties in with the JUnit 5 lifecycle.
How it works and why it is designed so
Inheritance models "is a kind of" (is-a) and tightly couples the descendant to the ancestor: the descendant receives everything that is not private and depends on how the ancestor implements it. In Java a class has only one ancestor, so a "base" cannot be assembled from several separate parts: everything somebody needs ends up in one class. Composition models "has" (has-a): an object holds other objects as fields and delegates work to them, and the same component is used by pages that have no common ancestor.
For BaseTest inheritance is justified, because what is shared is the run setup itself. JUnit 5 calls the ancestor's @BeforeEach methods before the descendant's, and @AfterEach in the reverse order, so the ancestor can prepare the environment for the descendant and clean up after it. For BasePage the limit is narrower: it should hold only what every page needs.
abstract class BaseTest {
protected WebDriver driver;
@BeforeEach
void startBrowser() { // runs before the subclass @BeforeEach
driver = DriverFactory.create(Config.browser());
}
@AfterEach
void stopBrowser() { // runs after the subclass @AfterEach
if (driver != null) driver.quit();
}
}
class LoginTest extends BaseTest {
@Test
void validUserSeesDashboard() {
new LoginPage(driver).open().loginAs(Users.standard());
}
}
There are two small things here that spoil life. The first is visible in the names: if a descendant declares a method with the same signature as the ancestor's @BeforeEach, the ancestor's method is overridden and does not run, so the driver does not start. So lifecycle methods get unique names (startBrowser, not the setUp everybody writes). The second: @BeforeAll and @AfterAll must be static, while the driver field stays non-static, so that every test instance has its own browser (more in the next lesson).
Example: from a chain of ancestors to composition
The fragile variant: the hierarchy grows deep, because each level adds what the next one needs.
class BasePage { /* driver, waits */ }
class CommonPage extends BasePage { /* header, footer */ }
class AuthPage extends CommonPage { /* sign-in form */ }
class LoginPage extends AuthPage { /* LoginPage inherited everything above */ }
The fix: a thin base and components that a page holds as fields.
abstract class BasePage {
protected final WebDriver driver;
private final WebDriverWait wait;
protected BasePage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
protected WebElement visible(By locator) {
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
}
class HeaderComponent { // not a page, has no ancestor
private static final By USER_MENU = By.id("user-menu");
private final WebDriver driver;
HeaderComponent(WebDriver driver) { this.driver = driver; }
String userName() { return driver.findElement(USER_MENU).getText(); }
}
class OrdersPage extends BasePage {
private final HeaderComponent header;
OrdersPage(WebDriver driver) {
super(driver);
this.header = new HeaderComponent(driver); // composition
}
HeaderComponent header() { return header; }
OrdersPage openOrder(String id) {
visible(By.cssSelector("[data-order='" + id + "']")).click();
return this; // fluent
}
}
Inheritance and composition
LoginPage → AuthPage → CommonPage → BasePage
A change in an ancestor touches all descendants; every page drags methods it does not need.
OrdersPage has HeaderComponent and DataTable
A component changes in one place, and a page takes only what it needs.
After the change HeaderComponent is described in one class, and BasePage knows only about the driver and waits. The openOrder method returns this, and a navigation method returns the next page: loginPage.loginAs(u).openOrders(). This way the scenario reads as a sequence of actions, and the compiler will not let you call a method of a page the user is no longer on.
Limits and alternatives
- The rule "the test asserts, the page acts" is not a dogma: a page may expose state (
isErrorShown(),errorText()), and the test compares it. Assertions in a page tie it to one library and one scenario. - Access: locators and helper methods are
private, actions for tests arepublic, what descendants need isprotected. Note thatprotectedalso opens the whole package. - Another alternative to a base test class in JUnit 5 is an extension (
@ExtendWith,@RegisterExtension): it manages the driver as a resource, and a test plugs it in with one line and does not have to inherit anything. - For API tests, a separate
BaseApiTestwith a client, not a shared ancestor with the UI tests: they do not need a browser.
Common mistakes
- A "god object"
BasePagewith page methods for everything: every page depends on things it does not use. - A page hierarchy deeper than two levels for reuse that composition gives as well.
- A
setUpin a descendant overrides the ancestor'ssetUp: the driver is not created, and the test fails withNullPointerException. - Test data and expectations in
BaseTestthat three tests out of a hundred need: they belong in separate classes or fixtures.
Check yourself
BaseTest has @BeforeEach void setUp() that starts the driver, and in LoginTest a developer also wrote @BeforeEach void setUp() for data. What happens?
Answer
The descendant method overrides the ancestor method, so the BaseTest version does not run. The driver stays null and the first access to it throws NullPointerException. The fix: unique names for lifecycle methods.
When is composition better than inheritance for shared page logic?
Answer
When the shared part does not concern all pages: a header, a table, a modal. They are extracted into component fields, and the ancestor stays thin and carries only the driver and waits.
BaseTest holds shared setup and cleanup (driver, configuration), BasePage holds what pages share. Inheritance models "is a kind of", and a component such as a header is held by a page as a field. Middle/Senior: I keep base classes thin: Java has only one ancestor, so "everything somebody needs" in the base quickly bloats it. I extract shared UI parts into components, give lifecycle methods unique names so as not to override the ancestor, and when needed hand resource management to a JUnit extension. I keep assertions in tests and let the page expose state.