For example: Blog Park landing page:
The codes for non-pagefactory and @findby are as follows
public class LoginPage1 {
Defines three webelement attributes, which are used to record three page elements of user name, password, login button
Webdriver driver;
Webelement username;
webelement password;
Webelement Loginbutton;
Public LoginPage1 (Webdriver driver) {
This.driver = driver;
Username = driver.findelement (by.id ("input1"));
Password = driver.findelement (by.id ("Input2"));
Loginbutton = Driver.findelement (By.id ("signin"));
}
Define a login () method for sending a user name and password and logging on to the website
public void Login (String username,string passWord) {
Username.sendkeys (username);
Password.sendkeys (password);
Loginbutton.click ();
Driver.manage (). Timeouts (). implicitlywait (3, timeunit.seconds);
}
}
The code for Pagefactory and @findby is as follows
public class LoginPage2 {
Webdriver driver;
Any page element in the page can be tagged with @findby annotations.
@FindBy can be used to replace the lookup mechanism of the drive.findelement () method to locate page elements
@FindBy (how = How.id,id = "INPUT1")
Webelement username;
@FindBy (how = how.id,id= "Input2")
webelement password;
@FindBy (how = how.id,id= "Signin")
Webelement Loginbutton;
Public LoginPage2 (Webdriver driver) {
This.driver = driver;
}
public void Login (String username,string passWord) {
Username.sendkeys (username);
Password.sendkeys (password);
Loginbutton.click ();
Driver.manage (). Timeouts (). implicitlywait (3, timeunit.seconds);
}
}
In contrast: The code using the @findby annotation pattern is clearer, and the @findby (how = How.id,id = "xx") in the constructor replaces a series of driver.findelement (By.id ("XX"));
Send a message for example
Non-pagefactor Factory mode
public void SendMessage (String touser,string titleconent,string textconent) {
Entermessagebox ();
Newmessage = Driver.findelement (By.linktext ("Compose new text message"));
Newmessage.click ();
SendMessagePage1 sendmessagepage = new SendMessagePage1 (driver);
Sendmessagepage.sendnewmessage (Touser, titleconent, textconent);
}
Pagefactor Factory mode
public void SendMessage (String touser,string titlecontent,string textconten) {
Entermessagebox ();
Newmessage.click ();
SendMessagePage2 sendmessagepage = pagefactory.initelements (driver, sendmessagepage2.class);
Sendmessagepage.sendnewmessage (Touser, titlecontent, Textconten);
}
In contrast: The code using the Pagefactor factory model is clearer, pagefactory.initelements (driver, Sendmessagepage2.class) replaces the new SendMessagePage1 ( driver); instantiation
Use of pagefactory and @findby annotations