How to use PageFactory class of org.openqa.selenium.support package

Best Selenium code snippet using org.openqa.selenium.support.PageFactory

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.orasi.core.interfaces.impl.internal;
2
3import java.lang.reflect.Constructor;
4import java.lang.reflect.InvocationTargetException;
5
6import org.openqa.selenium.WebDriver;
7import org.openqa.selenium.support.PageFactory;
8import org.openqa.selenium.support.pagefactory.FieldDecorator;
9
10import com.orasi.exception.automation.PageInitialization;
11import com.orasi.utils.OrasiDriver;
12import com.orasi.utils.TestReporter;
13
14/**
15 * Element factory for wrapped elements. Similar to {@link org.openqa.selenium.support.PageFactory}
16 */
17public class ElementFactory {
18
19    /**
20     *  See {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.WebDriver driver, Class)}
21     */
22    public static <T> T initElements(OrasiDriver driver, Class<T> pageClassToProxy) {
23		TestReporter.logTrace("Entering ElementFactory#initElements");
24		TestReporter.logTrace("Creating Page Object");
25        T page = instantiatePage(driver, pageClassToProxy);
26		TestReporter.logTrace("Successfully created Page Object");
27        final OrasiDriver driverRef = driver;
28		TestReporter.logTrace("Initialize Page Elements");
29        PageFactory.initElements(new ElementDecorator(new CustomElementLocatorFactory(driverRef)), page);
30		TestReporter.logTrace("Successfully created Page Elements");
31		TestReporter.logTrace("Exiting ElementFactory#initElements");
32        return page;
33    }
34
35    /**
36     *  See {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.FieldDecorator, Object)}
37     */
38    public static void initElements(OrasiDriver driver, Object page) {
39		TestReporter.logTrace("Entering ElementFactory#initElements");
40        final OrasiDriver driverRef = driver;
41		TestReporter.logTrace("Initialize Page Elements");
42        PageFactory.initElements(new ElementDecorator(new CustomElementLocatorFactory(driverRef), driverRef), page);
43		TestReporter.logTrace("Successfully created Page Elements");
44		TestReporter.logTrace("Exiting ElementFactory#initElements");
45    }
46
47    /**
48     * see {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.ElementLocatorFactory, Object)}
49     */
50    public static void initElements(CustomElementLocatorFactory factory, Object page) {
51		TestReporter.logTrace("Entering ElementFactory#initElements");
52        final CustomElementLocatorFactory factoryRef = factory;
53		TestReporter.logTrace("Initialize Page Elements");
54        PageFactory.initElements(new ElementDecorator(factoryRef), page);
55		TestReporter.logTrace("Successfully created Page Elements");
56		TestReporter.logTrace("Exiting ElementFactory#initElements");
57    }
58
59    /**
60     * see {@link org.openqa.selenium.support.PageFactory#initElements(org.openqa.selenium.support.pagefactory.ElementLocatorFactory, Object)}
61     */
62    public static void initElements(FieldDecorator decorator, Object page) {
63		TestReporter.logTrace("Entering ElementFactory#initElements");
64		TestReporter.logTrace("Initialize Page Elements");
65        PageFactory.initElements(decorator, page);
66		TestReporter.logTrace("Successfully created Page Elements");
67		TestReporter.logTrace("Exiting ElementFactory#initElements");
68    }
69
70    /**
71     * Copy of {@link org.openqa.selenium.support.PageFactory#instantiatePage(org.openqa.selenium.WebDriver, Class)}
72     */
73    private static <T> T instantiatePage(WebDriver driver, Class<T> pageClassToProxy) {
74		TestReporter.logTrace("Entering ElementFactory#instantiatePage");
75        try {
76            try {
77            	TestReporter.logTrace("Create Constructor of Page object");
78                Constructor<T> constructor = pageClassToProxy.getConstructor(WebDriver.class);
79            	TestReporter.logTrace("Successfully created Constructor");
80
81            	TestReporter.logTrace("Create new instance of Page object");
82            	T instance = constructor.newInstance(driver);
83            	TestReporter.logTrace("Successfully created new Page instance");
84        		TestReporter.logTrace("Exiting ElementFactory#instantiatePage");
85                return instance;
86            } catch (NoSuchMethodException e) {
87        	try{            		
88        		TestReporter.logTrace("Entering ElementFactory#instantiatePage");
89        		return pageClassToProxy.newInstance();
90        	}catch(InstantiationException ie){ 
91        		throw new PageInitialization("Failed to create instance of: " + pageClassToProxy.getName(), driver);
92        	}
93            }
94        } catch (InstantiationException e) {
95            throw new PageInitialization("Failed to create instance of: " + pageClassToProxy.getName(), driver);
96        } catch (IllegalAccessException e) {
97            throw new RuntimeException(e);
98        } catch (InvocationTargetException e) {
99            throw new RuntimeException(e);
100        }
101    }
102}
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17package org.openqa.selenium.support;
18
19import org.junit.runner.RunWith;
20import org.junit.runners.Suite;
21import org.openqa.selenium.support.events.EventFiringWebDriverTest;
22import org.openqa.selenium.support.pagefactory.AjaxElementLocatorTest;
23import org.openqa.selenium.support.pagefactory.AnnotationsTest;
24import org.openqa.selenium.support.pagefactory.ByAllTest;
25import org.openqa.selenium.support.pagefactory.ByChainedTest;
26import org.openqa.selenium.support.pagefactory.DefaultElementLocatorTest;
27import org.openqa.selenium.support.pagefactory.DefaultFieldDecoratorTest;
28import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandlerTest;
29import org.openqa.selenium.support.pagefactory.internal.LocatingElementListHandlerTest;
30import org.openqa.selenium.support.ui.ExpectedConditionsTest;
31import org.openqa.selenium.support.ui.FluentWaitTest;
32import org.openqa.selenium.support.ui.HowTest;
33import org.openqa.selenium.support.ui.LoadableComponentTest;
34import org.openqa.selenium.support.ui.QuotesTest;
35import org.openqa.selenium.support.ui.SelectTest;
36import org.openqa.selenium.support.ui.SlowLoadableComponentTest;
37import org.openqa.selenium.support.ui.WebDriverWaitTest;
38
39@RunWith(Suite.class)
40@Suite.SuiteClasses({
41    AjaxElementLocatorTest.class,
42    AnnotationsTest.class,
43    ByChainedTest.class,
44    ByAllTest.class,
45    ColorTest.class,
46    DefaultElementLocatorTest.class,
47    DefaultFieldDecoratorTest.class,
48    EventFiringWebDriverTest.class,
49    ExpectedConditionsTest.class,
50    FluentWaitTest.class,
51    HowTest.class,
52    LoadableComponentTest.class,
53    LocatingElementHandlerTest.class,
54    LocatingElementListHandlerTest.class,
55    PageFactoryTest.class,
56    SelectTest.class,
57    QuotesTest.class,
58    SlowLoadableComponentTest.class,
59    ThreadGuardTest.class,
60    WebDriverWaitTest.class
61})
62public class SmallTests {}
63
Full Screen
copy
1 public class Element : IWrapsElement
2{
3    public IWebElement WrappedElement { get; set; }
4    public Element(IWebElement element)
5    {
6        this.WrappedElement = element;
7    }
8}
9
Full Screen
copy
1 public class Checkbox : Element
2{
3    public Checkbox(IWebElement element) : base(element) { }
4
5    public void Check(bool expected)
6    {
7        if (this.IsChecked()!= expected)
8        {
9            this.WrappedElement.Click();
10        }
11    }
12
13    public bool IsChecked()
14    {
15        return this.WrappedElement.GetAttribute("checked") == "true";
16    }
17}
18
Full Screen
copy
1Checkbox x = new Checkbox(driver.FindElement(By.Id("xyz")));
2x.Check(true)
3
Full Screen
copy
1 private IWebElement _chkMale{ get; set; }
2 [FindsBy(How = How.Name, Using = "chkMale")]
3
4 private Checkbox ChkMale
5    {
6        get { return new Checkbox (_chkMale); }
7    }
8ChkMale.Check(true);
9
Full Screen
copy
1class WEBElment
2{
3
4public IWebElement Element;
5
6public WEBElement(/*send whatever you decide, a webelement, a by element, a locator whatever*/)
7
8{
9
10Element = /*make the element from what you sent your self*/
11
12}
13
14
15public bool IsDisplayed()
16
17{
18
19return Element.Displayed;
20
21}
22
23} // end of class here
24
Full Screen
copy
1public class PermissionsPage extends TableWebElement{
2
3...permissions stuff...
4
5}
6
7import WebElement
8
9public class TableWebElement{
10
11...custom web elements pertaining to my page...
12
13}
14
Full Screen
copy
1public class UserList
2 {
3private UserListPage page;
4
5UserList(WebDriver driver)
6{
7    page = new UserListPage(driver);
8}
9
10public void deleteFirstTwoUsers()
11{
12    if (page.userList.size() <2) throw new RuntimeException("Terrible bug!");  
13
14    page.deleteUserButtons.get(0).click();
15    page.deleteUserButtons.get(0).click();
16}
17
18class UserListPage {
19
20@FindBy(xpath = "//span[@class='All_Users']")
21List<BaseElement> userList;
22
23@FindBy(xpath = "//span[@class='All_Users_Delete_Buttons']")
24List<BaseElement> deleteUserButtons;
25
26UserListPage(WebDriver driver)
27 {
28    PageFactory.initElements(new ExtendedFieldDecorator(driver), this);
29 }
30}
31
Full Screen
copy
1public void deleteFirstTwoUsers()
2{
3    if (page.userList.size() <2) throw new RuntimeException("Terrible bug!");  
4
5    new UserListPage(driver).deleteUserButtons.get(0).click();
6    new UserListPage(driver).deleteUserButtons.get(1).click();
7}
8
Full Screen
copy
1public class UserList {
2  private WebDriver driver;
3
4UserList(WebDriver driver)
5{
6    this.driver = driver;
7}
8
9UserListPage getPage { return new UserListPage(driver);})
10public void deleteFirstTwoUsers()
11{
12    if (getPage.userList.size() <2) throw new RuntimeException("Terrible bug!");  
13
14    getPage.deleteUserButtons.get(0).click();
15    getPage.deleteUserButtons.get(0).click();
16}
17
Full Screen
copy
1class UserListPage
2{
3private WebDriver driver;
4
5UserListPage(WebDriver driver)
6{
7    this.driver = driver;
8}
9
10List<BaseElement> getUserList() {
11    return driver.findElements(By.xpath("//span[@class='All_Users']"));
12}
13
Full Screen
copy
1public class TableWebElement implements WebElement {
2
Full Screen
copy
1public class WebUI{
2  private WebDriver driver;    
3  private WebElement permissionTable;   
4
5   public WebUI(){
6      driver = new firefoxDriver();
7   }
8
9  public WebDriver getDriver(){
10     return driver;
11  }
12
13  public WebElement getPermissionTable(){
14     return permissionTable;
15  }
16
17  public TableWebElement getTable(){
18     permissionTable = driver.findElement(By.id("studyPermissionsTable"));
19     return new TableWebElement(this);
20  }
21}
22
Full Screen
copy
1public class TableWebElement{
2  private WebUI webUI;
3
4 public TableWebElement(WebUI wUI){
5    this.webUI = wUI;
6 }
7
8 public int getTableSize() {
9    // because I dont know exactly what are you trying to achieve just few hints
10    // this is how you get to the WebDriver:
11    WebElement element = webUI.getDriver().findElement(By.id("foo"));
12
13    //this is how you get to already found table:
14    WebElement myTable = webUI.getPermissionTable();
15
16 }
17
18}
19
Full Screen
copy
1 @Test
2 public void testTableSize(){
3    WebUI web = new WebUI();
4    TableWebElement myTable = web.getTable();
5    Assert.assertEquals(myTable.getSize(), 25);
6 }
7
Full Screen
copy
1public class CustomTable {
2
3private WebDriver driver;
4private WebElement tableWebElement;
5
6public CustomTable(WebElement table, WebDriver driver) {
7    this.driver = driver;
8    tableWebElement = table;
9}
10
11public WebElement getTableWebElement() {
12    return tableWebElement;
13}
14
15public List<WebElement> getTableRows() {
16    String id = tableWebElement.getAttribute("id");
17    return driver.findElements(By.xpath("//*[@id='" + id + "']/tbody/tr"));
18}
19
20public List<WebElement> getTableHeader() {
21    String id = tableWebElement.getAttribute("id");
22    return tableWebElement.findElements(By.xpath("//*[@id='" + id + "']/thead/tr/th"));
23}   
24.... more utility functions here
25}
26
Full Screen
copy
1public class TestPage {
2
3@FindBy(id = "testTable")
4private WebElement myTestTable;
5
6/**
7 * @return the myTestTable
8 */
9public CustomTable getBrowserTable() {
10    return new CustomTable(myTestTable, getDriver());
11}
12
Full Screen
copy
1public class Table extends WebComponent {
2    @FindBy(tagName = "tr")
3    List<Row> rows;
4
5    public Row getRow(int row) {
6        return rows.get(row - 1);
7    }
8
9    public int getTableSize() {
10        return rows.size();
11    }
12
13    public static class Row extends WebComponent {
14        @FindBy(tagName = "td")
15        List<WebElement> columns;
16
17        public WebElement getCell(int column) {
18            return columns.get(column - 1);
19        }
20    }
21}
22
Full Screen
copy
1public class PermissionPage {
2    public PermissionPage(WebDriver driver) {
3        PageFactory.initElements(new WebDriverExtensionFieldDecorator(driver), this);
4    }
5
6    @FindBy(id = "studyPermissionsTable")
7    public Table permissionTable;
8
9    @FindBy(id = "studyPermissionAddPermission")
10    public WebElement addPermissionButton;
11}
12
Full Screen
copy
1public class PermissionPageTest {
2    @Test
3    public void exampleTest() {
4        WebDriver driver = new FirefoxDriver();
5        PermissionPage permissionPage = new PermissionPage(driver);
6
7        driver.get("http://www.url-to-permission-page.com");
8        assertEquals(25, permissionPage.permissionTable.getTableSize());
9        assertEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1).getText());
10        assertEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2).getText());
11        assertEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3).getText());
12    }
13}
14
Full Screen
copy
1public class PermissionPage extends WebPage {
2    @FindBy(id = "studyPermissionsTable")
3    public Table permissionTable;
4
5    @FindBy(id = "studyPermissionAddPermission")
6    public WebElement addPermissionButton;
7
8    @Override
9    public void open(Object... arguments) {
10        open("http://www.url-to-permission-page.com");
11        assertIsOpen();
12    }
13
14    @Override
15    public void assertIsOpen(Object... arguments) throws AssertionError {
16        assertIsDisabled(permissionTable);
17        assertIsDisabled(addPermissionButton);
18    }
19}
20
Full Screen
copy
1import static com.github.webdriverextensions.Bot.*;
2
3@RunWith(WebDriverRunner.class)
4public class PermissionPageTest {
5
6    PermissionPage permissionPage;
7
8    @Test
9    @Firefox
10    public void exampleTest() {
11        open(permissionPage);
12        assertSizeEquals(25, permissionPage.permissionTable.rows);
13        assertTextEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1));
14        assertTextEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2));
15        assertTextEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3));
16    }
17}
18
Full Screen
copy
1public interface Element extends WebElement, WrapsElement, Locatable {}
2
Full Screen
copy
1public class ElementImpl implements Element {
2
3    private final WebElement element;
4
5    public ElementImpl(final WebElement element) {
6        this.element = element;
7    }
8
9    @Override
10    public void click() {
11        element.click();
12    }
13
14    @Override
15    public void sendKeys(CharSequence... keysToSend) {
16        element.sendKeys(keysToSend);
17    }
18
19    // And so on, delegates all the way down...
20
21}
22
Full Screen
copy
1public class CheckBox extends ElementImpl {
2
3    public CheckBox(WebElement element) {
4        super(element);
5    }
6
7    public void toggle() {
8        getWrappedElement().click();
9    }
10
11    public void check() {
12        if (!isChecked()) {
13            toggle();
14        }
15    }
16
17    public void uncheck() {
18        if (isChecked()) {
19            toggle();
20        }
21    }
22
23    public boolean isChecked() {
24        return getWrappedElement().isSelected();
25    }
26}
27
Full Screen
copy
1CheckBox cb = new CheckBox(element);
2cb.uncheck();
3
Full Screen
copy
1public class PageObject {
2    private static final String XPATH_NAME = "...";
3
4    public @iOSXCUITFindBy(xpath = XPATH_NAME)
5    List<MobileElement> mobileElementName;
6
7    public By getByXPath(){
8        return new By.ByXPath(XPATH_NAME);
9    }
10
11    public PageObject() {
12        PageFactory.initElements(driver, this);
13    }
14}
15
Full Screen
copy
1private String getLocatorFromWebElement(WebElement element) {
2
3    return element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "");
4}
5
Full Screen
copy
1<dependency>
2    <groupId>org.apache.commons</groupId>
3    <artifactId>commons-lang3</artifactId>
4    <version>3.7</version>
5</dependency>
6
Full Screen
copy
1protected String getLocator(WebElement element) {
2        try {
3            Object proxyOrigin = FieldUtils.readField(element, "h", true);
4            Object locator = FieldUtils.readField(proxyOrigin, "locator", true);
5            Object findBy = FieldUtils.readField(locator, "by", true);
6            if (findBy != null) {
7                return findBy.toString();
8            }
9        } catch (IllegalAccessException ignored) {
10        }
11        return "[unknown]";
12    }
13
Full Screen
copy
1private By getByFromElement(WebElement element) {
2    By by = null;
3    //[[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]
4    String[] pathVariables = (element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "")).split(":");
5
6    String selector = pathVariables[0].trim();
7    String value = pathVariables[1].trim();
8
9    switch (selector) {
10        case "id":
11            by = By.id(value);
12            break;
13        case "className":
14            by = By.className(value);
15            break;
16        case "tagName":
17            by = By.tagName(value);
18            break;
19        case "xpath":
20            by = By.xpath(value);
21            break;
22        case "cssSelector":
23            by = By.cssSelector(value);
24            break;
25        case "linkText":
26            by = By.linkText(value);
27            break;
28        case "name":
29            by = By.name(value);
30            break;
31        case "partialLinkText":
32            by = By.partialLinkText(value);
33            break;
34        default:
35            throw new IllegalStateException("locator : " + selector + " not found!!!");
36    }
37    return by;
38}
39
Full Screen
copy
1public class RefreshableWebElement implements WebElement {
2
3    public RefreshableWebElement(Driver driver, By by) {
4        this.driver = driver;
5        this.by = by;
6    }
7
8    // ...
9
10    public WebElement getElement() {
11        return driver.findElement(by);
12    }
13
14    public void click() {
15        getElement().click();
16    }
17
18    // other methods here
19}
20
Full Screen
copy
1By by = By.id("someId");
2WebElement e = driver.findElement(by);
3
Full Screen
copy
1....
2DateWidget widget = new DateWidget(driver, "yearId", "monthId", "dayId");
3....
4
5public void testYearNumeric() {
6        widget.setYear("aa");
7        widget.submit();
8        //Logic to determine Error message shows up
9
10        // ... and day
11        widget.setDay("bb");
12        widget.submit();
13        //Logic to determine Error message shows up
14    }
15
Full Screen
copy
1package pagefactory.test;
2
3import java.lang.reflect.Field;
4
5import org.openqa.selenium.By;
6import org.openqa.selenium.WebDriver;
7import org.openqa.selenium.WebElement;
8import org.openqa.selenium.support.FindBy;
9import org.openqa.selenium.support.PageFactory;
10import org.openqa.selenium.support.pagefactory.Annotations;
11import org.openqa.selenium.support.pagefactory.ElementLocator;
12import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;
13import org.openqa.selenium.support.ui.ExpectedCondition;
14import org.openqa.selenium.support.ui.Wait;
15import org.openqa.selenium.support.ui.WebDriverWait;
16
17public class DateWidget {
18
19    // These constants are used to identify that they should be changed to the actual IDs
20    private static final String YEAR_ID = "$YEAR_ID$";
21    private static final String MONTH_ID = "$MONTH_ID$";
22    private static final String DAY_ID = "$DAY_ID$";
23
24    // Elements whose ids will be replaced during run-time
25    /** Year element */
26    @FindBy(id = YEAR_ID)
27    private WebElement year;
28
29    /** Month element */
30    @FindBy(id = MONTH_ID)
31    private WebElement month;
32
33    /** day element */
34    @FindBy(id = DAY_ID)
35    private WebElement day;
36
37    // The ids of the elements
38    /** ID of the year element */
39    private String yearId;
40
41    /** ID of the month element */
42    private String monthId;
43
44    /** ID of the day element */
45    private String dayId;
46
47    public DateWidget(WebDriver driver, String yearId, String monthId,
48            String dayId) {
49        this.yearId = yearId;
50        this.monthId = monthId;
51        this.dayId = dayId;
52
53        PageFactory.initElements(new CustomLocatorFactory(driver, 15), this);
54    }
55
56    public String getYear() {
57        return year.getValue();
58    }
59
60    public void setYear(String year) {
61        setValue(this.year, year);
62    }
63
64    public String getMonth() {
65        return month.getValue();
66    }
67
68    public void setMonth(String month) {
69        setValue(this.month, month);
70    }
71
72    public String getDay() {
73        return day.getValue();
74    }
75
76    public void setDay(String day) {
77        setValue(this.day, day);
78    }
79
80    public void submit() {
81        year.submit();
82    }
83
84    private void setValue(WebElement field, String value) {
85        field.clear();
86        field.sendKeys(value);
87    }
88
89    private class CustomLocatorFactory implements ElementLocatorFactory {
90        private final int timeOutInSeconds;
91        private WebDriver driver;
92
93        public CustomLocatorFactory(WebDriver driver, int timeOutInSeconds) {
94            this.driver = driver;
95            this.timeOutInSeconds = timeOutInSeconds;
96        }
97
98        public ElementLocator createLocator(Field field) {
99            return new CustomElementLocator(driver, field, timeOutInSeconds);
100        }
101    }
102
103    private class CustomElementLocator implements ElementLocator {
104        private WebDriver driver;
105        private int timeOutInSeconds;
106        private final By by;
107
108        public CustomElementLocator(WebDriver driver, Field field,
109                int timeOutInSeconds) {
110            this.driver = driver;
111            this.timeOutInSeconds = timeOutInSeconds;
112            CustomAnnotations annotations = new CustomAnnotations(field);
113            this.by = annotations.buildBy();
114        }
115
116        @Override
117        public WebElement findElement() {
118            ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
119                public Boolean apply(WebDriver d) {
120                    d.findElement(by);
121                    return Boolean.TRUE;
122                }
123            };
124            Wait<WebDriver> w = new WebDriverWait(driver, timeOutInSeconds);
125            w.until(e);
126
127            return driver.findElement(by);
128        }
129    }
130
131    private class CustomAnnotations extends Annotations {
132
133        public CustomAnnotations(Field field) {
134            super(field);
135        }
136
137        @Override
138        protected By buildByFromShortFindBy(FindBy findBy) {
139
140            if (!"".equals(findBy.id())) {
141                String id = findBy.id();
142                if (id.contains(YEAR_ID)) {
143                    id = id.replace(YEAR_ID, yearId);
144                    return By.id(id);
145                } else if (id.contains(MONTH_ID)) {
146                    id = id.replace(MONTH_ID, monthId);
147                    return By.id(id);
148                } else if (id.contains(DAY_ID)) {
149                    id = id.replace(DAY_ID, dayId);
150                    return By.id(id);
151                }
152            }
153
154            return super.buildByFromShortFindBy(findBy);
155        }
156
157    }
158
159}
160
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in PageFactory

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)