java-client icon indicating copy to clipboard operation
java-client copied to clipboard

Unable to initialise PageFactory for PageObject

Open ashishkumar1000 opened this issue 12 years ago • 40 comments

I have updated the java-client jar and tried to initialise PageFactory as mention below.

PageObject PageObject1 = PageFactory.initElements(new AppiumFieldDecorator(driver),PageObject.class);

But I am getting type mismatch error. Is there something I am missing ???

ashishkumar1000 avatar Jul 31 '14 05:07 ashishkumar1000

All right, I tried with the instance, and it works for me, but we still have more coding to do that way...

lolemouine avatar Aug 05 '14 13:08 lolemouine

I will create my AppiumPageFactory ! I understand wath you mean now !

lolemouine avatar Aug 05 '14 14:08 lolemouine

Oops! I have just thought about new PageFactory class for Appium! But I'm not sure that there are many projects where usage of page object instance instead of class is difficult. So I will keep track of situation...

Maybe it will be implemented.

TikhomirovSergey avatar Aug 05 '14 15:08 TikhomirovSergey

Any work arounds with iOS ? I am still facing issues in implementing Page Factory for iOS.

ashishkumar1000 avatar Sep 06 '14 14:09 ashishkumar1000

@ashishkumar1000 What issues are you facing?

TikhomirovSergey avatar Sep 08 '14 19:09 TikhomirovSergey

Did someone manage to implement Page Factory for iOS so far?

mbelyaeva91 avatar Aug 24 '15 07:08 mbelyaeva91

we do not have any problem with iOS and Android.

amedvedjev avatar Aug 24 '15 07:08 amedvedjev

I tried to follow the examples above and nothing works for me. What if we have more than one page? Do I initialize them all in @Before setUp()? I followed this sample https://github.com/appium/sample-code/blob/master/sample-code/examples/java/junit/src/test/java/com/saucelabs/appium/iOSPageObjectTest.java and it works fine with one page. I still don't get how to deal with multiple pages

mbelyaeva91 avatar Aug 24 '15 12:08 mbelyaeva91

"I tried to follow the examples above and nothing works for me. What if we have more than one page? Do I initialize them all in @Before setUp()?" - NOT. you should do this in test code. sample you follow is not perfect for creating multiple pages.

amedvedjev avatar Aug 24 '15 20:08 amedvedjev

There is so much going on in this thread that its hard to follow what we are saying is broken and what should be working so I am just going to provide my code and can someone explain why I am getting a NullPointerException? (Note, I have a similar setup in a selenium project and no issues).

public class AgentLoginPage extends BasePageClass {

    @iOSFindBy(xpath = "//UITextFieldLabel[@label = 'Email']")
    public static MobileElement emailInput;

    @iOSFindBy(xpath = "//UITextFieldLabel[@label = 'Password']")
    public static MobileElement passwordInput;

    public static void initialize(){
        // driver is pulled in from BasePageClass.
        PageFactory.initElements(new AppiumFieldDecorator(driver), AgentLoginPage.class);
    }

    @When("^I submit a \"(.*)\" agent login form$")  //Code for Cucumber.
    public static void I_submit_a_X_agent_login_form(String loginType){
        String email = "", password = "";

        switch (loginType.toLowerCase()){
            case "valid":
                email = "[email protected]";
                password = "Password";
                break;
            default:
                throw new PendingException("Unknown Login Type: " + loginType);
        }

        emailInput.sendKeys(email);   //NullPointerException here
        passwordInput.sendKeys(password);

        passwordInput.sendKeys(Keys.ENTER); //Submits form

    }
}

In my before Hooks:

        AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService();
        service.start();

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9.2");
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone 6 Plus");
        capabilities.setCapability(MobileCapabilityType.APP, appPath);
        capabilities.setCapability("name", "Java iOS tutorial " + date);

        driver = new IOSDriver(service.getUrl(), capabilities);

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        AgentLoginPage.initialize();

Can I not do this via a static variable? I would think it would be a non issue.

JasonSmiley208 avatar Feb 23 '16 21:02 JasonSmiley208

@JasonSmiley208 you do init in wrong place.

simplest example:

public abstract class Page {

    protected WebDriver driver;

    public Page(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(new AppiumFieldDecorator(driver, 20, TimeUnit.SECONDS), this);
    }
}

public class MainPage extends Page {

    //Action bar
    @AndroidFindBy(id = "action_bar_title")
    private List<AndroidElement> actionBarTitle;

    //List Elements
    @AndroidFindBy(id = "list")
    private List<AndroidElement> listView;
    @AndroidFindBy(id = "text1")
    private List<AndroidElement> cellText;

    public MainPage(WebDriver driver) {
        super(driver);
    }

    public boolean isMainPageLoaded() {
        return !actionBarTitle.isEmpty() && !listView.isEmpty();
    }
}

public class BaseTest {
    protected static AppiumDriver driver = null;
    private static DesiredCapabilities capabilities = null;
    ....

    @BeforeMethod(alwaysRun=true)
    public void beforeMethod(ITestContext iTestContext) {
        capabilities = DesiredCapabilities.android();
        capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Appium");
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);
        File appDir = new File(userDir, fileName);
        capabilities.setCapability(MobileCapabilityType.APP, appDir.getAbsolutePath());
        capabilities.setCapability(MobileCapabilityType.APP_WAIT_ACTIVITY, ".ApiDemos");
        capabilities.setCapability("fullReset", true);
        capabilities.setCapability("noReset", true);

        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    }

    @AfterMethod(alwaysRun=true)
    public void afterMethod(ITestResult iTestResult, ITestContext iTestContext) throws Exception {
        try {
            driver.quit();
        } catch (Exception e) {}
    }

    //... so on continue with @BeforeSuite, @AfterSuite, ..... whatever needed
}

public class test_1 extends BaseTest {
    private MainPage mainPage;

    @Test
    public void testMainPage() {
        mainPage = PageFactory.initElements(driver, MainPage.class);
        assertTrue("Main screen NOT loaded", mainPage.isMainPageLoaded());
   }
}

amedvedjev avatar Feb 24 '16 07:02 amedvedjev

Quick question - I see you are using

mainPage = PageFactory.initElements(driver, MainPage.class);

instead of

new AppiumFieldDecorator(driver)

Is that intended or a typo?

Or is this because you are using the Page(Webdriver) constructor?

JasonSmiley208 avatar Feb 24 '16 16:02 JasonSmiley208

are you sure - ? see:

public Page(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(new AppiumFieldDecorator(driver, 20, TimeUnit.SECONDS), this);
    }

amedvedjev avatar Feb 24 '16 16:02 amedvedjev

I am trying to setup POM with Appium and running into issue . I used the same code provided by TikhomirovSergey commented on Jul 31, 2014 ( Says : This code works) But I still get the Pagefactory error message . It is also looking and saying source jar not found looking in my selenium-server-standalone jar3.0.1

java.lang.IllegalArgumentException: Can not set static io.appium.java_client.MobileElement field wfm.appium.testcases.FinalApp$LandPageObject.CreateAccountnew to com.sun.proxy.$Proxy6 at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) at sun.reflect.UnsafeStaticObjectFieldAccessorImpl.set(UnsafeStaticObjectFieldAccessorImpl.java:79) at java.lang.reflect.Field.set(Field.java:764) at org.openqa.selenium.support.PageFactory.proxyFields(PageFactory.java:117) at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:105) at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:92) at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:79) at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:65) at wfm.appium.testcases.FinalApp.test(FinalApp.java:73) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

idcmurali avatar Dec 01 '16 16:12 idcmurali

Hi @TikhomirovSergey , I use the "legal way"(2) you mentioned above, but it doesn't work, I got noSuchMethod error when using sendKeys.

In Abstract BasePage: protected BasePage(AndroidDriver<AndroidElement> driver){ this.driver = driver; PageFactory.initElements(new AppiumFieldDecorator(driver, 5, TimeUnit.SECONDS), this); }

LoginPage extends BasePage: ` @AndroidFindBy(id = "et_login_username") private AndroidElement usernameField;

public LoginPage(AndroidDriver driver){ super(driver); }`

In LoginTest: `@Override @BeforeClass public void setUpPage() {

objLogin = new LoginPage(driver);

} And I got NoSuchMethodError on usernameField.sendKeys(strUsername);`

Appreciate it if you could help out!

klzeng avatar Jul 07 '17 06:07 klzeng

Hi i got the same error NoSuchMethodError. please anyone help me. i upgrade dependencies to latest versions .

Pageobjectpage, Note: static import the iosDriver Class LoginPage(){ public LoginPage() { PageFactory.initElements(new AppiumFieldDecorator(iosDriver,15, TimeUnit.SECONDS), this);}

@iOSFindBy(xpath="//XCUIElementTypeButton[7]") private MobileElement Number1Btn;

public void login(){ Number1Btn.click(); } }

LoginTest

public class LoginTest extends BaseTest{ private LoginPage loginPage; @BeforeClass public void setup() { loginpage = new LoginPage(); }

@Test public void loginTest() { loginPage.login();-----------------this line shows Nosuch method error }

my reports,

java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.FluentWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object; at io.appium.java_client.pagefactory.AppiumElementLocator.waitFor(AppiumElementLocator.java:88) at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:103) at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:57) at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$184e91dc.click()

rmeenasuresh avatar Jul 10 '17 16:07 rmeenasuresh

Its still reproducible on Appium 1.8.1 :( Anyone resolve this?

narendra-chandratre avatar Aug 08 '18 08:08 narendra-chandratre

This Working with Me, My Project Selenium, TestNG and Appium use PageFactory.initElements

public class Login extends Setup {

    @Test
    public void loginAlert() throws InterruptedException {
        

    Button button = new Button(driver);
            PageFactory.initElements(driver, button);
            Input input = new Input(driver);
            PageFactory.initElements(driver, input);
        
        
        Input input1 = new Input(driver);
        System.out.println("Test Alert Login");
        button.ById("navigation_more");
        button.ById("btnLogin");
        input.ById("et_email_or_phone_number", "dikakoko.com");
        input1.ById("tet_password", "dikakoko");
        
    }
}

Below this is the function I called above.

public class Input {
    AppiumDriver<MobileElement> driver;
    Root root = new Root();

    public Input(AppiumDriver<MobileElement> driver) {
        this.driver = driver;
    }

    public void ById(String selector, String textValue) {
        MobileElement element = driver.findElement(By.id(root.element() + ":id/" + selector));
        waitForVisible(driver, element);
        Actions actions = new Actions(driver);
        actions.moveToElement(element);
        actions.click();
        actions.sendKeys(textValue);
        actions.build().perform();
        System.out.println("Input: " + textValue);
    }
    
    private void waitForVisible(AppiumDriver<MobileElement> driver, MobileElement element) {
        try {
            Thread.sleep(5000);
            System.out.println("Waiting for element visibility");
            WebDriverWait wait = new WebDriverWait(driver, 20);
            wait.until(ExpectedConditions.visibilityOf(element));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

and This


public class Button {

    AppiumDriver<MobileElement> driver;
    Root root = new Root();

    public Button(AppiumDriver<MobileElement> driver) {
        this.driver = driver;
    }

    public void ById(String selector) {
        MobileElement element = driver.findElement(By.id(root.element() + ":id/" + selector));
        Actions actions = new Actions(driver);
        actions.moveToElement(element);
        actions.click();
        actions.build().perform();
        System.out.println("Button is Clicked!");
    }
}

I Use This

             Button button = new Button(driver);
            PageFactory.initElements(driver, button);
            Input input = new Input(driver);
            PageFactory.initElements(driver, input);

References : www.seleniumeasy.com

dikako avatar Jul 06 '20 14:07 dikako

Try these steps: This might help (Works in my case with same initElement NoSuchMethod Exception)

Open Eclipse> Windows> Preferences> Java> Installed JREs> Change the selected JRE to the JDK: (Follow the steps:) Add the Java folder(C:\Program Files\Java\jdk-11.0.14) as JDK (Installed) Select that added JDK, then Apply and close.

image

Try retest your scripts after this change.

MukeshHalaPlay avatar Feb 17 '22 16:02 MukeshHalaPlay

Hai guys any one please help me ! I'm not able to use appiumfielddecorator, if I use appiumfielddecorator, I'm getting this exception: java.lang.ExceptionInInitializerError at io.appium.java_client.pagefactory.u tils.ProxyFactory.getEnhanced Prox y(ProxyFactory.java:53)

: I am automating Mobile app (Android ). So If I use PageFactory.initElements (driver, this); and try to find elements by using annotation as @FindBy MY CODE WORKS.

But if try to use PageFactory.initElements (new AppiumFieldDecorator (driver), this); and try to find elements by using annotation as @AndroidFindBy My CODE is not working, and I'm getting the exception java.lang.ExceptionInInitializerError.

I'm using jdk version 17 Java client 8.2.0 Appium also latest 1.2.3 This is my code : public class Page1 { // page object class

public static AppiumDriver driver;

public Page1(AppiumDriver driver) {
    PageFactory.initElements(new AppiumFieldDecorator(driver), this);
    this.driver = driver;
}


@AndroidFindBy(id = "com.tva.z5:id/homeIcon")
public WebElement homeIcon;

public void logo() {
    homeIcon.click();

}

}


package appiumtests; // this is my test

public class Test1 {

@Test
public void test() throws InterruptedException {

    Page1 lg = new Page1(driver);

      lg.logo();
    Thread.sleep(5000);

}

}

Demudu1995 avatar Oct 30 '22 14:10 Demudu1995