Bird
Raised Fist0
Selenium Javatesting~20 mins

Test class consuming page objects in Selenium Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Page Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of test method using page object
Given the following test class using a page object, what will be the output when the test runs successfully?
Selenium Java
public class LoginPage {
    private WebDriver driver;
    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }
    public void enterUsername(String username) {
        driver.findElement(By.id("username")).sendKeys(username);
    }
    public void enterPassword(String password) {
        driver.findElement(By.id("password")).sendKeys(password);
    }
    public void clickLogin() {
        driver.findElement(By.id("loginBtn")).click();
    }
    public String getWelcomeMessage() {
        return driver.findElement(By.id("welcomeMsg")).getText();
    }
}

public class LoginTest {
    WebDriver driver = new ChromeDriver();
    LoginPage loginPage = new LoginPage(driver);

    @Test
    public void testValidLogin() {
        driver.get("http://example.com/login");
        loginPage.enterUsername("user1");
        loginPage.enterPassword("pass1");
        loginPage.clickLogin();
        String message = loginPage.getWelcomeMessage();
        System.out.println(message);
    }
}
APrints "Welcome user1!" to the console
BThrows NoSuchElementException at enterUsername
CPrints empty string because welcomeMsg element is missing
DThrows NullPointerException at clickLogin
Attempts:
2 left
💡 Hint
Think about what the page object methods do and what the getWelcomeMessage returns after login.
❓ assertion
intermediate
1:30remaining
Correct assertion for login success
Which assertion correctly verifies that the login was successful by checking the welcome message using the page object?
Selenium Java
String expectedMessage = "Welcome user1!";
String actualMessage = loginPage.getWelcomeMessage();
AassertNull(actualMessage);
BassertEquals(expectedMessage, actualMessage);
CassertFalse(actualMessage.isEmpty());
DassertTrue(actualMessage.contains("user1"));
Attempts:
2 left
💡 Hint
Check which assertion exactly compares the expected and actual welcome messages.
❓ locator
advanced
1:30remaining
Best locator for login button in page object
Which locator is the best practice to use for the login button in the page object class to ensure stability and readability?
ABy.cssSelector("button.btn-primary")
BBy.xpath("//button[text()='Login']")
CBy.id("loginBtn")
DBy.className("btn")
Attempts:
2 left
💡 Hint
Consider uniqueness and stability of locators.
🔧 Debug
advanced
2:00remaining
Identify cause of NoSuchElementException in test
A test using a page object fails with NoSuchElementException at the line driver.findElement(By.id("password")).sendKeys("pass1");. What is the most likely cause?
AThe driver instance is null
BThe id "password" is misspelled in the page object
CThe sendKeys method is called before driver.get()
DThe password input field is not present on the current page
Attempts:
2 left
💡 Hint
Think about what causes NoSuchElementException in Selenium.
❓ framework
expert
3:00remaining
Proper test class structure using page objects and JUnit 5
Which test class structure correctly uses JUnit 5 annotations and page objects to initialize WebDriver before all tests and quit after all tests?
A
public class LoginTest {
    static WebDriver driver;
    static LoginPage loginPage;

    @BeforeAll
    public static void setup() {
        driver = new ChromeDriver();
        loginPage = new LoginPage(driver);
    }

    @AfterAll
    public static void teardown() {
        driver.quit();
    }

    @Test
    public void testLogin() {
        driver.get("http://example.com/login");
        loginPage.enterUsername("user1");
        loginPage.enterPassword("pass1");
        loginPage.clickLogin();
        assertEquals("Welcome user1!", loginPage.getWelcomeMessage());
    }
}
B
public class LoginTest {
    WebDriver driver = new ChromeDriver();
    LoginPage loginPage = new LoginPage(driver);

    @BeforeEach
    public void setup() {
        driver = new ChromeDriver();
        loginPage = new LoginPage(driver);
    }

    @AfterEach
    public void teardown() {
        driver.quit();
    }

    @Test
    public void testLogin() {
        driver.get("http://example.com/login");
        loginPage.enterUsername("user1");
        loginPage.enterPassword("pass1");
        loginPage.clickLogin();
        assertEquals("Welcome user1!", loginPage.getWelcomeMessage());
    }
}
C
public class LoginTest {
    static WebDriver driver;
    LoginPage loginPage;

    @BeforeAll
    public void setup() {
        driver = new ChromeDriver();
        loginPage = new LoginPage(driver);
    }

    @AfterAll
    public void teardown() {
        driver.quit();
    }

    @Test
    public void testLogin() {
        driver.get("http://example.com/login");
        loginPage.enterUsername("user1");
        loginPage.enterPassword("pass1");
        loginPage.clickLogin();
        assertEquals("Welcome user1!", loginPage.getWelcomeMessage());
    }
}
D
public class LoginTest {
    WebDriver driver;
    LoginPage loginPage;

    @BeforeEach
    public void setup() {
        driver = new ChromeDriver();
        loginPage = new LoginPage(driver);
    }

    @AfterAll
    public void teardown() {
        driver.quit();
    }

    @Test
    public void testLogin() {
        driver.get("http://example.com/login");
        loginPage.enterUsername("user1");
        loginPage.enterPassword("pass1");
        loginPage.clickLogin();
        assertEquals("Welcome user1!", loginPage.getWelcomeMessage());
    }
}
Attempts:
2 left
💡 Hint
Remember that @BeforeAll and @AfterAll methods must be static in JUnit 5.

Practice

(1/5)
1. What is the main purpose of a test class when it consumes page objects in Selenium Java?
easy
A. To locate web elements directly using Selenium locators
B. To manage browser driver setup and teardown only
C. To define the structure of the web page elements
D. To perform test steps and assertions using methods from page objects

Solution

  1. 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.
  2. Step 2: Identify test class responsibility

    Test classes call page object methods to execute test steps and verify results with assertions.
  3. Final Answer:

    To perform test steps and assertions using methods from page objects -> Option D
  4. Quick Check:

    Test class runs tests using page objects [OK]
Hint: Test classes call page object methods to run tests [OK]
Common Mistakes:
  • Trying to locate elements directly in test class
  • Mixing page object code with test logic
  • Using test class only for driver setup
2. Which of the following is the correct way to instantiate a page object in a Selenium Java test class?
easy
A. LoginPage login = new LoginPage(driver);
B. LoginPage login = LoginPage();
C. LoginPage login = new LoginPage();
D. LoginPage login = driver.get(LoginPage.class);

Solution

  1. Step 1: Recall page object constructor usage

    Page objects usually require WebDriver passed to constructor for element initialization.
  2. 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.
  3. Final Answer:

    LoginPage login = new LoginPage(driver); -> Option A
  4. Quick Check:

    Use 'new' with driver parameter [OK]
Hint: Always pass driver to page object constructor [OK]
Common Mistakes:
  • Forgetting to pass driver to constructor
  • Using constructor without 'new' keyword
  • Trying to get page object from driver directly
3. Given the following test class snippet, what will be the output if the login fails?
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.
medium
A. Login Failed
B. Compilation error
C. Login Successful
D. Runtime exception

Solution

  1. Step 1: Understand login method behavior

    login() returns true if credentials are correct, false otherwise.
  2. Step 2: Analyze given credentials and output

    Credentials are wrong, so login() returns false, printing "Login Failed".
  3. Final Answer:

    Login Failed -> Option A
  4. Quick Check:

    False login returns "Login Failed" [OK]
Hint: Check boolean return to decide output [OK]
Common Mistakes:
  • Assuming login returns exception on failure
  • Confusing true/false return values
  • Ignoring ternary operator logic
4. Identify the error in this test class code snippet that uses a page object:
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");
  }
}
medium
A. Test method missing assertion
B. WebDriver is not initialized before use
C. LoginPage constructor is called without passing driver
D. Missing @After method to quit driver

Solution

  1. Step 1: Check page object instantiation

    LoginPage requires driver in constructor, but called without arguments here.
  2. Step 2: Confirm driver initialization

    Driver is initialized correctly before page object creation, so no issue there.
  3. Final Answer:

    LoginPage constructor is called without passing driver -> Option C
  4. Quick Check:

    Page object needs driver in constructor [OK]
Hint: Always pass driver when creating page objects [OK]
Common Mistakes:
  • Forgetting driver parameter in page object constructor
  • Assuming driver auto-initializes in page object
  • Ignoring missing assertions (not error here)
5. You want to write a test class that uses two page objects: 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?
hard
A. Write all element locators and actions inside the test class without page objects
B. Instantiate both page objects with driver, call login on HomePage, then call updateProfile on ProfilePage, finally assert success message from ProfilePage
C. Create one page object combining HomePage and ProfilePage methods, then test all steps there
D. Use driver directly in test class to click and send keys for all steps

Solution

  1. Step 1: Understand separation of concerns

    Page objects encapsulate page details; test class uses them to perform test steps and assertions.
  2. 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.
  3. Final Answer:

    Instantiate both page objects with driver, call login on HomePage, then call updateProfile on ProfilePage, finally assert success message from ProfilePage -> Option B
  4. Quick Check:

    Test class calls page objects methods in flow [OK]
Hint: Use separate page objects, call their methods in test class [OK]
Common Mistakes:
  • Putting all locators and actions in test class
  • Combining unrelated page objects into one
  • Using driver directly instead of page objects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard