0
0
Selenium Javatesting~10 mins

PageFactory initialization in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page and verifies that a button is present using Selenium's PageFactory to initialize web elements.

Test Code - JUnit 5 with Selenium
Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.*;

public class PageFactoryTest {
    WebDriver driver;

    @FindBy(id = "submit-btn")
    WebElement submitButton;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://example.com");
        PageFactory.initElements(driver, this);
    }

    @Test
    public void testSubmitButtonIsDisplayed() {
        Assertions.assertTrue(submitButton.isDisplayed(), "Submit button should be visible");
    }

    @AfterEach
    public void tearDown() {
        driver.quit();
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test class-PASS
2Browser opens ChromeDriverChrome browser window opens-PASS
3Navigates to https://example.comBrowser loads the example.com homepage-PASS
4PageFactory initializes elements annotated with @FindBysubmitButton WebElement is linked to element with id 'submit-btn'-PASS
5Checks if submitButton is displayedsubmitButton element is visible on the pageAssert that submitButton.isDisplayed() returns truePASS
6Test ends and browser closesChrome browser window closes-PASS
Failure Scenario
Failing Condition: The submit button is not visible on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does PageFactory.initElements do in this test?
AIt navigates to the URL
BIt opens the browser window
CIt links the WebElement fields to actual elements on the page
DIt closes the browser
Key Result
Using PageFactory.initElements helps keep your test code clean by automatically linking WebElement fields to page elements, making tests easier to read and maintain.