简体   繁体   中英

Using @FindBy in Selenium without PageFactory

I've been able to successfully use @FindBy with PageFactory but the person training me insists that I can still use @FindBy without using PageFactory. He showed me his code and from a quick glance, it does seem like he isn't using PageFactory. However, without using PageFactory, I always get the NullPointerException. I did ask him to look at my code and ...well he doesn't seem to know why my code does not work either. I'm hoping I could get fresh pairs of eyes to enlighten me.

Here is a snippet of my code

public class BaseClass {

public WebDriver driver;
private String title;
private Wait<WebDriver> wait;

public BaseClass(WebDriver driver, String title) {

    this.driver = driver;
    this.title = title;
    wait = new FluentWait<WebDriver>(driver).withTimeout(45, TimeUnit.SECONDS).pollingEvery(2, TimeUnit.SECONDS);
}
}

//

public class Test extends BaseClass {


public Test(WebDriver driver) {
    super(driver, "Login page");

}


@FindBy(name="j_password")
public WebElement password;

@FindBy(name="j_username")
public WebElement username;

public void startest() throws Exception {
username.clear();
username.sendKeys(id);
password.clear();
password.sendKeys(secret); }
}

No you cannot use without using PageFactory . Read the below lines for proper explanation :

Page Factory will initialize every WebElement variable with a reference to a corresponding element on the actual web page based on “locators” defined. This is done by using @FindBy annotations.

Annotations?

In Page Factory, Annotations are used to give descriptive names for WebElements to improve code readability. And annotation @FindBy is used to identify Web Elements in the page.

By default, PageFactory will search for elements on the page with a matching id attribute, If that fails, then it will search by the name attribute. But as we need more control over identifying elements in the HTML page and mapping them to our Page Object fields.

Following link has more details : http://www.seleniumeasy.com/selenium-tutorials/page-factory-pattern-in-selenium-webdriver

Yes, you can do it without Selenium's PageFactory, but it means you need to implement your own equivalent of it.

The PageFactory doesn't do anything magical to create/populate the elements. It's power is in how it does some of the more advanced things like caching and only populating at the time the elements are referenced (which in the C# implementation is done by using a RealProxy, not sure of the Java equivalent).

Another option is to store By properties, and evaluate them as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM