上一篇介绍了POM的基础理论知识和非POM方式写脚本,这篇介绍利用页面工厂类(page factory)去实现POM,通过查看PageFactory类,我们可以知道它是一个初始化一个页面实例的功能,在实例化该页面对象时候,也会一起实例化该页面的元素定位。
在这里宏哥以百度首页登录的例子,如果用POM实现,在测试脚本中实际代码就几行。
1.先新建一个pageObjects包,然后在pageObjects包新建一个百度主页类:BaiduHomePage,代码设计如下图所示:

2.再次新建一个testSuites包,然后在testSuites包下新建一个测试类:TestWithPOM

1.BaiduHomePage
package pageObjects;import org.openqa.selenium.WebElement;import org.openqa.selenium.support.FindBy;/** * @author 北京-宏哥 * * @公众号:北京宏哥 * * 《手把手教你》系列基础篇(八十七)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-上篇(详解教程) * * 2022年3月20日 */public class BaiduHomePage { // 元素定位 // 登录按钮 @FindBy(xpath="//*[@id='u1']/a[1]") WebElement login_link; // 输入用户名框 @FindBy(xpath="//*[@id='TANGRAM__PSP_11__userName']") WebElement inputBox_username; // 输入密码 @FindBy(xpath="//*[@id='TANGRAM__PSP_11__passwordWrapper']/input[2]") WebElement inputBox_password; // 登录按钮 @FindBy(id = "TANGRAM__PSP_11__submit") WebElement login_submitBtn; // 业务逻辑和操作方法 // 登录方法 public void login(String username, String password) throws InterruptedException { login_link.click(); Thread.sleep(3000); inputBox_username.sendKeys(username); inputBox_password.sendKeys(password); login_submitBtn.click(); }}
2.TestWithPOM
package testSuites;import org.testng.annotations.Test;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.support.PageFactory;import org.testng.annotations.BeforeClass;import pageObjects.BaiduHomePage;/** * @author 北京-宏哥 * * @公众号:北京宏哥 * * 《手把手教你》系列基础篇(八十七)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-上篇(详解教程) * * 2022年3月20日 */public class TestWithPOM { WebDriver driver; @BeforeClass public void setUp() throws Exception{ System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.baidu.com/"); Thread.sleep(2000); } @Test public void testLogin() throws InterruptedException{ BaiduHomePage hp = PageFactory.initElements(driver, BaiduHomePage.class); hp.login("user1", "123456"); } }
1.运行代码,右键Run AS->TestNG Suite,控制台输出,如下图所示:

2.运行代码后电脑端的浏览器的动作,如下小视频所示:
好了今天主要介绍和讲解了百度首页登录使用POM和不使用POM。二者的优缺点一目了然,宏哥在这里就不多说了,今天就到这里了,感谢您耐心的阅读!!!
