Page Object Model in Appium

Some important points

  1. If you have worked with Selenium Page factory, you already know page object model
  2. Each page of the app is represented by the page class
  3. Advantage of using page object model is that maintainance becomes very easy. When elements on one page change, we need to make changes at one place only.
  4. We need to use PageFactory class to work with Page object models

Below example shows how to create the class for a Page.
package org.softpost.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.softpost.BasePage;

public class Home extends BasePage{

    public Home(WebDriver driver)
    {
        super(driver);
        PageFactory.initElements(driver,this);
    }

    @FindBy (xpath = "//input")
    WebElement e1;

    public void clickBattery(){
        WebElement battery = driver.findElement(By.xpath("//android.widget.TextView[contains(@text,'Battery')]"));
        battery.click();
    }

}


Our Home page class extends the BasePage below

package org.softpost;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class BasePage {
    protected WebDriver driver;
    public BasePage(WebDriver driver){
    this.driver = driver;
    }
}

Below example shows how to access above page object model in tests

package org.softpost.tests;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.softpost.pages.Home;

import java.net.URL;
import java.util.concurrent.TimeUnit;

public class MyTests {

    WebDriver driver;

    @Test
    public void test() throws Exception{


        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("platformName", "android");

        caps.setCapability("deviceName", "Pixel 9");
        caps.setCapability("appPackage", "com.android.settings");
        caps.setCapability("appActivity","com.android.settings.Settings");
        caps.setCapability("automationName","uiautomator2");

        try {
            driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

            Thread.sleep(5000);
            Home home = new Home(driver);
            home.clickBattery();
            Thread.sleep(5000);


        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }finally{
            driver.quit();
        }
    }
}


Youtube | Facebook | Twitter | Website Home | Online Grocery Shopping Brisbane