HomePage Class

Learn how to implement user interactions with the Home Page in the HomePage class using element locators.

The code of the HomePage class is shown below:

Press + to interact
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import framework.LogWriter;
public class HomePage {
private static final By SEARCH_BOX_ID = By.id("edit-search");
private static final By SEARCH_BUTTON_ID = By.id("edit-submit");
private final WebDriver driver;
private final WebDriverWait wait;
private final LogWriter traceLogWriter;
public HomePage(WebDriver driver)
{
this.driver = driver;
this.wait = new WebDriverWait(driver, 30);
this.traceLogWriter = new LogWriter("./target/logs", "trace.log");
}
public ResultsPage searchFor(String keyword)
{
typeKeyword(keyword);
executeSearch();
traceLogWriter.writeToLog("HomePage - searchFor()");
return goToResultsPage();
}
private ResultsPage goToResultsPage()
{
ResultsPage resultsPage = new ResultsPage(driver);
traceLogWriter.writeToLog("HomePage - goToResultsPage()");
if (!resultsPage.isDisplayed())
throw new ElementNotVisibleException(
"Results Page is not displayed!");
return resultsPage;
}
private void typeKeyword(String keyword)
{
wait.until(d -> d.findElement(SEARCH_BOX_ID).isEnabled());
WebElement searchBox = driver.findElement(SEARCH_BOX_ID);
searchBox.sendKeys(keyword);
}
private void executeSearch()
{
wait.until(d -> d.findElement(SEARCH_BUTTON_ID).isEnabled());
WebElement searchButton = driver.findElement(SEARCH_BUTTON_ID);
searchButton.click();
}
}

Why do we need this class?

The HomePage class implements the user interactions with the Home Page of the site. In our case, the only thing that the user does on the Home Page is execute a keyword search.

Constructor

The HomePage constructor gets the driver as a parameter and saves it in a class variable (lines 21-23).

It also creates a WebDriverWait object with the 30 seconds timeout (line 24). This object will be used for waiting for elements to be visible ...