告别屎山代码!测试工程师必学的Page Object模式,效率提升70%
还在为UI自动化测试的维护噩梦头疼?一个登录按钮改了ID,要改100个测试脚本?2025年最火的Page Object模式来了!作为测试工程师,我用这套方案让团队维护成本直降70%,手把手教你玩转PO模式!
科普:什么是Page Object模式?
PO模式 = 把每个页面变成Python类!
三大核心思想:
- 元素定位 → 封装成类属性
- 操作行为 → 封装成类方法
- 业务流 → 方法组合调用
传统 vs PO模式对比:
传统:page.locator("#login-btn").click() 散落在100个脚本里
PO模式:login_page.click_login() 统一维护,一次修改全局生效
实战:电商系统PO架构设计
分层架构:
text
pages/
├── login_page.py # 登录页封装
├── home_page.py # 首页封装
└── cart_page.py # 购物车封装
1. 登录页封装(高可复用版)
python
class LoginPage:
def __init__(self, page):
self.page = page
self.username = page.get_by_placeholder("手机号/邮箱") # 推荐:面向用户定位
self.password = page.get_by_label("密码")
self.submit_btn = page.get_by_role("button", name="登录")
def login(self, user, pwd): # 业务语义封装!
self.username.fill(user)
self.password.fill(pwd)
self.submit_btn.click()
expect(self.page).to_have_url("**/dashboard") # 自动等待
测试技巧:
用get_by_role/text替代CSS选择器,稳定性提升90%!
2. 购物车页封装(含智能断言)
python
class CartPage:
def apply_coupon(self, code):
self.page.get_by_test_id("coupon-input").fill(code) # 测试ID最稳定!
self.page.get_by_text("应用优惠券").click()
expect(self.page.get_by_text("优惠券已生效")).to_be_visible() # 自动等待+断言
科普小知识:
什么是testid定位?
给元素加data-testid属性,前端怎么改样式都不影响测试!
三大高阶技巧
1. 组件化复用(Header抽离)
python
class HeaderComponent: # 头部导航抽成组件
def __init__(self, page):
self.search_bar = page.get_by_role("searchbox")
class HomePage:
def __init__(self, page):
self.header = HeaderComponent(page) # 直接复用!
def search(self, keyword):
self.header.search(keyword) # 调用组件方法
2. 多用户隔离测试
python
# conftest.py
@pytest.fixture
def user_context(playwright):
context = playwright.chromium.new_context(
storage_state="user1.json" # 复用登录态
)
yield context
context.close() # 自动清理
3. 并发抢购测试
python
def test_concurrent_purchase():
with ThreadPoolExecutor() as executor:
# 3用户并发下单
futures = [executor.submit(place_order, user) for user in ["u1","u2","u3"]]
assert all("成功" in f.result() for f in futures)
四大避坑指南
- 元素失效 → 只用get_by_role/testid/text定位
- 异步加载 → PO方法内必须加wait_for_selector
- 页面跳转 → 返回新页面对象:return OrderPage(self.page)
- 多语言 → 文本抽离到locales/zh-CN.json
测试工程师总结
必做:
- 所有元素定位器必须集中管理
- 业务操作封装成login()这种语义化方法
- 多用Playwright的expect自动等待
效果:
- 新页面接入速度提升50%
- 元素变更只需改1个文件
- 用例可读性暴涨,产品经理都能看懂!
现在就用PO模式重构你的测试框架,让同事直呼专业!更多请戳 >>>
https://ceshiren.com/t/topic/34346
#自动化测试 #测试开发 #PageObject #Playwright #代码重构