Test class consuming page objects in Selenium Java - Build an Automation Script
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.*; // Page Object for Login Page class LoginPage { private WebDriver driver; private WebDriverWait wait; private By usernameInput = By.id("username"); private By passwordInput = By.id("password"); private By loginButton = By.cssSelector("button[type='submit']"); public LoginPage(WebDriver driver) { this.driver = driver; this.wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } public void enterUsername(String username) { WebElement userField = wait.until(ExpectedConditions.visibilityOfElementLocated(usernameInput)); userField.clear(); userField.sendKeys(username); } public void enterPassword(String password) { WebElement passField = wait.until(ExpectedConditions.visibilityOfElementLocated(passwordInput)); passField.clear(); passField.sendKeys(password); } public void clickLogin() { WebElement button = wait.until(ExpectedConditions.elementToBeClickable(loginButton)); button.click(); } public void loginAs(String username, String password) { enterUsername(username); enterPassword(password); clickLogin(); } } // Page Object for Dashboard Page class DashboardPage { private WebDriver driver; private WebDriverWait wait; private By welcomeMessage = By.id("welcome-msg"); public DashboardPage(WebDriver driver) { this.driver = driver; this.wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } public boolean isWelcomeMessageDisplayed() { return wait.until(ExpectedConditions.visibilityOfElementLocated(welcomeMessage)).isDisplayed(); } public String getWelcomeMessageText() { return driver.findElement(welcomeMessage).getText(); } } public class LoginTest { private WebDriver driver; private LoginPage loginPage; private DashboardPage dashboardPage; @BeforeEach public void setUp() { driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://example.com/login"); loginPage = new LoginPage(driver); dashboardPage = new DashboardPage(driver); } @Test public void testValidLogin() { loginPage.loginAs("testuser", "Test@1234"); // Wait for URL to contain '/dashboard' new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.urlContains("/dashboard")); assertTrue(driver.getCurrentUrl().contains("/dashboard"), "URL should contain '/dashboard'"); assertTrue(dashboardPage.isWelcomeMessageDisplayed(), "Welcome message should be displayed"); assertEquals("Welcome, testuser", dashboardPage.getWelcomeMessageText(), "Welcome message text should match"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
The code uses the Page Object Model to separate page interactions from the test logic.
LoginPage class handles entering username, password, and clicking login with explicit waits to ensure elements are ready.
DashboardPage class checks for the welcome message presence and text.
The LoginTest class sets up the ChromeDriver, opens the login page, uses the page objects to perform login, then asserts the URL and welcome message.
Explicit waits ensure the test waits for the page to load and elements to appear before interacting or asserting.
Finally, the browser is closed in the tearDown method to clean up.
Now add data-driven testing with 3 different sets of login credentials (valid and invalid) using JUnit 5 parameterized tests.
Practice
Solution
Step 1: Understand roles of test class and page objects
Page objects encapsulate web element locators and actions. Test classes use these to perform tests.Step 2: Identify test class responsibility
Test classes call page object methods to execute test steps and verify results with assertions.Final Answer:
To perform test steps and assertions using methods from page objects -> Option DQuick Check:
Test class runs tests using page objects [OK]
- Trying to locate elements directly in test class
- Mixing page object code with test logic
- Using test class only for driver setup
Solution
Step 1: Recall page object constructor usage
Page objects usually require WebDriver passed to constructor for element initialization.Step 2: Check each option for correct syntax
LoginPage login = new LoginPage(driver); correctly uses 'new' with driver argument. Others miss driver or use invalid syntax.Final Answer:
LoginPage login = new LoginPage(driver); -> Option AQuick Check:
Use 'new' with driver parameter [OK]
- Forgetting to pass driver to constructor
- Using constructor without 'new' keyword
- Trying to get page object from driver directly
LoginPage login = new LoginPage(driver);
boolean result = login.login("wrongUser", "wrongPass");
System.out.println(result ? "Login Successful" : "Login Failed");Assuming
login() returns true on success and false on failure.Solution
Step 1: Understand login method behavior
login() returns true if credentials are correct, false otherwise.Step 2: Analyze given credentials and output
Credentials are wrong, so login() returns false, printing "Login Failed".Final Answer:
Login Failed -> Option AQuick Check:
False login returns "Login Failed" [OK]
- Assuming login returns exception on failure
- Confusing true/false return values
- Ignoring ternary operator logic
public class LoginTest {
WebDriver driver;
LoginPage loginPage;
@Before
public void setup() {
driver = new ChromeDriver();
loginPage = new LoginPage();
}
@Test
public void testLogin() {
loginPage.login("user", "pass");
}
}Solution
Step 1: Check page object instantiation
LoginPage requires driver in constructor, but called without arguments here.Step 2: Confirm driver initialization
Driver is initialized correctly before page object creation, so no issue there.Final Answer:
LoginPage constructor is called without passing driver -> Option CQuick Check:
Page object needs driver in constructor [OK]
- Forgetting driver parameter in page object constructor
- Assuming driver auto-initializes in page object
- Ignoring missing assertions (not error here)
HomePage and ProfilePage. You want to test the flow: login, navigate to profile, update info, and verify success message. Which approach best follows the test class consuming page objects pattern?Solution
Step 1: Understand separation of concerns
Page objects encapsulate page details; test class uses them to perform test steps and assertions.Step 2: Evaluate options for best practice
Instantiate both page objects with driver, call login on HomePage, then call updateProfile on ProfilePage, finally assert success message from ProfilePage correctly uses separate page objects and test class calls their methods in sequence.Final Answer:
Instantiate both page objects with driver, call login on HomePage, then call updateProfile on ProfilePage, finally assert success message from ProfilePage -> Option BQuick Check:
Test class calls page objects methods in flow [OK]
- Putting all locators and actions in test class
- Combining unrelated page objects into one
- Using driver directly instead of page objects
Ready to prove it?
Pass the test and this pattern moves unknown
