Test Overview
This test opens a web page and verifies that a button is present using Selenium's PageFactory to initialize web elements.
This test opens a web page and verifies that a button is present using Selenium's PageFactory to initialize web elements.
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(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes the test class | — | PASS |
| 2 | Browser opens ChromeDriver | Chrome browser window opens | — | PASS |
| 3 | Navigates to https://example.com | Browser loads the example.com homepage | — | PASS |
| 4 | PageFactory initializes elements annotated with @FindBy | submitButton WebElement is linked to element with id 'submit-btn' | — | PASS |
| 5 | Checks if submitButton is displayed | submitButton element is visible on the page | Assert that submitButton.isDisplayed() returns true | PASS |
| 6 | Test ends and browser closes | Chrome browser window closes | — | PASS |
PageFactory.initElements() in Selenium Java?initElements method scans the class for @FindBy annotations and initializes those elements.PageFactory.initElements(WebDriver driver, Object page).driver is passed first, then this refers to the current Page Object instance.loginButton.isDisplayed() is called after PageFactory initialization?public class LoginPage {
@FindBy(id = "loginBtn")
private WebElement loginButton;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
}
// In test method:
LoginPage page = new LoginPage(driver);
boolean visible = page.loginButton.isDisplayed();
System.out.println(visible);loginButton is declared private, so it cannot be accessed directly from outside the LoginPage class in the test method.page.loginButton.isDisplayed() causes a compilation error; private fields require public getter methods for external access. PageFactory initializes the field but does not change its visibility.public class HomePage {
@FindBy(name = "searchBox")
WebElement searchInput;
public HomePage(WebDriver driver) {
initElements(driver, this);
}
}initElements must be called with the class name PageFactory as PageFactory.initElements(...).Pass the test and this pattern moves unknown