Selenium Java Page Object Model Example 1
File: HomePage.java
package pageObjects;

import org.openqa.selenium.*;

public class HomePage
{
    static String actualTitle, expectedTitle;
    static WebElement logout = null;
    
    public static String title(WebDriver driver)
    {
        actualTitle = driver.getTitle();
        expectedTitle = "Welcome: Mercury Tours";
        if(actualTitle.equalsIgnoreCase(expectedTitle))
        {
            System.out.println("Page Title Matched");
        }
        else
        {
            System.out.println("Page Title Not Matched");
        }
        return actualTitle;
    }
}
File: LoginPage.java
package pageObjects;

import org.openqa.selenium.*;

public class LoginPage
{
    private static WebElement element = null;
    public static WebElement username(WebDriver driver)
    {
        element = driver.findElement(By.name("userName"));
        return element;
    }
    
    public static WebElement password(WebDriver driver)
    {
        element = driver.findElement(By.name("password"));
        return element;
    }
    
    public static WebElement login(WebDriver driver)
    {
        element = driver.findElement(By.name("login"));
        return element;
    }
    
    public static WebElement logout(WebDriver driver)
    {
        element = driver.findElement(By.xpath("//*[@class='mouseOut']//*[text()='SIGN-OFF']"));
        return element;
    }
}
File: TestCase.java
package test;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import pageObjects.HomePage;
import pageObjects.LoginPage;

public class TestCase
{
    private static WebDriver driver = null;
    public static void main(String[] args)
    {
        System.setProperty("webdriver.chrome.driver", "/home/kodingwindow/drivers/chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://newtours.demoaut.com/");
        
        System.out.println("Actual Title - "+HomePage.title(driver));
        LoginPage.username(driver).sendKeys("mercury");
        LoginPage.password(driver).sendKeys("mercury");
        LoginPage.login(driver).click();
        LoginPage.logout(driver).click();
        System.out.println("Sign-Off Successfully");
        driver.quit();
    }
}
Package Explorer

Advertisement