现代测试自动化框架教程:Behave接口测试与Airtest移动端UI自动化
前言
我发现每天还是陆陆续续有人在看我之前写的自动化框架搭建的文档;即使很早就有新的框架,更好的选择出来了;所以特别写了这一篇目前大厂也在使用的;日活400w有实际落地的自动化测试架构方案;
随着测试技术的发展,传统的pytest+selenium框架已经不能满足当今多样化的测试需求。本教程将介绍两种现代测试框架:Behave(用于接口自动化测试)和Airtest(用于移动端UI自动化测试),特别针对新手设计,从环境搭建到实际应用全面讲解。
一、Behave框架入门:行为驱动开发(BDD)接口测试
1.1 Behave框架简介
Behave是一个基于Python的行为驱动开发(BDD)工具,它使用自然语言描述测试场景,使非技术人员也能理解测试用例1。与传统的pytest不同,Behave特别适合接口自动化测试,因为它:
-
使用Gherkin语言编写测试用例(Feature、Scenario、Given-When-Then)
-
支持清晰的测试报告和文档生成
-
易于与非技术团队成员协作
-
提供丰富的钩子函数(before/after场景、步骤等)
1.2 环境搭建
首先确保已安装Python(建议3.7+),然后安装Behave:
pip install behave
pip install requests # 用于HTTP请求
pip install allure-behave # 可选,用于生成漂亮报告
1.3 项目结构
一个标准的Behave项目结构如下5:
features/
│
├── api.feature # 特性文件,用自然语言描述测试
├── environment.py # 环境配置和钩子函数
└── steps/└── api_steps.py # 步骤实现代码
1.4 编写第一个接口测试
1. 创建特性文件(features/api.feature):
Feature: 用户API测试作为系统管理员我需要验证用户API的功能以确保系统正常运行Scenario: 获取用户列表Given 准备请求头When 发送GET请求到"https://api.example.com/users"Then 响应状态码应该是200And 响应应该包含用户列表
2. 实现步骤定义(steps/api_steps.py):
from behave import given, when, then
import requests@given('准备请求头')
def step_impl(context):context.headers = {'Content-Type': 'application/json'}@when('发送GET请求到"{url}"')
def step_impl(context, url):context.response = requests.get(url, headers=context.headers)@then('响应状态码应该是{status_code}')
def step_impl(context, status_code):assert context.response.status_code == int(status_code)@then('响应应该包含用户列表')
def step_impl(context):assert 'users' in context.response.json()
3. 运行测试:
behave features/api.feature
1.5 高级功能:环境控制和报告生成
在environment.py
中可以添加钩子函数控制测试环境5:
def before_all(context):# 在所有测试之前运行context.base_url = "https://api.example.com"def after_step(context, step):# 在每个步骤之后运行if step.status == "failed":print(f"步骤失败: {step.name}")
要生成Allure报告:
behave -f allure_behave.formatter:AllureFormatter -o report/ features/
allure serve report/
1.6 实际应用示例:测试RESTful API
结合Requests库,可以轻松测试各种HTTP方法610:
# steps/api_steps.py
@when('以{username}和{password}登录')
def step_impl(context, username, password):data = {'username': username, 'password': password}context.response = requests.post(f"{context.base_url}/login",json=data,headers=context.headers)
二、Airtest框架:移动端UI自动化测试
2.1 Airtest框架简介
Airtest是由网易开发的UI自动化测试框架,特别适合移动端(Android/iOS)测试,具有以下特点:
-
基于图像识别的元素定位,不依赖具体UI代码
-
支持Poco框架进行UI层次结构定位
-
内置IDE方便脚本录制和调试
-
支持跨平台(Windows、Mac、Linux)
2.2 环境搭建
安装Airtest IDE和Python库:
pip install airtest
pip install pocoui # Poco框架
下载Airtest IDE:官方下载地址
2.3 项目结构
典型的Airtest项目结构:
mobile_tests/
│
├── cases/
│ ├── login.air # Airtest测试脚本
│ └── search.air
├── reports/ # 测试报告
└── utils/ # 公共方法
2.4 编写第一个移动端测试
1. 连接设备:
在Airtest IDE中连接Android/iOS设备或模拟器。对于Android,确保已启用USB调试模式。
2. 录制测试脚本:
使用Airtest IDE的录制功能创建login.air
脚本:
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco# 初始化Poco
poco = AndroidUiautomationPoco()# 启动应用
start_app("com.example.app")# 输入用户名和密码
poco("com.example.app:id/username").set_text("testuser")
poco("com.example.app:id/password").set_text("password123")# 点击登录按钮
poco("com.example.app:id/login_btn").click()# 验证登录成功
assert_exists(Template(r"tpl/home_screen.png"))
3. 运行测试:
airtest run login.air --device Android:///
2.5 高级功能:路由跳转与图像识别
当应用支持路由跳转时,测试可以大大简化:
# 直接通过路由跳转到目标页面
poco("com.example.app:id/nav_button").click()
wait(Template(r"tpl/target_page.png"))# 或者使用路由URL
start_app("com.example.app://user/profile")
图像识别是Airtest的核心功能:
# 等待某个图片出现
touch(Template(r"tpl/button.png"))# 或者
if exists(Template(r"tpl/popup.png")):touch(Template(r"tpl/close_btn.png"))
2.6 生成测试报告
Airtest自动生成HTML报告,也可以与Allure集成:
airtest report login.air --log_root ./logs --export ./report
三、Behave与Airtest结合的最佳实践
3.1 混合框架架构
结合两种框架的优势,可以构建强大的测试体系:
tests/
│
├── api/ # 接口测试
│ ├── features/
│ └── steps/
│
├── mobile/ # 移动端测试
│ ├── cases/
│ └── reports/
│
└── shared/ # 共享代码├── utils/└── config.py
3.2 共享测试数据
通过环境变量或配置文件共享测试数据:
# shared/config.py
TEST_USER = {'username': 'testuser','password': 'password123'
}
3.3 持续集成配置
Jenkins CI配置示例:
pipeline {agent anystages {stage('API Tests') {steps {sh 'behave ./tests/api/features --junit'}}stage('Mobile Tests') {steps {sh 'airtest run ./tests/mobile/cases/login.air --device Android:///'}}}post {always {allure includeProperties: false, jdk: '', results: [[path: 'tests/api/reports']]archiveArtifacts artifacts: 'tests/mobile/reports/**'}}
}
四、常见问题与解决方案
4.1 Behave常见问题
Q: 步骤定义找不到?
A: 确保步骤文件在steps/
目录下,且文件名以_steps.py
结尾5
Q: 如何传递数据between步骤?
A: 使用context
对象,如context.user_id = response.json()['id']
4.2 Airtest常见问题
Q: 无法识别元素?
A: 尝试:
-
使用Poco Inspector确认元素路径
-
增加等待时间
poco(text="Login").wait(10).click()
-
使用图像识别作为后备
Q: 测试在不同设备上不稳定?
A: 使用相对定位或更宽松的图像匹配阈值:
Template(r"tpl/button.png", threshold=0.7)
五、总结与进阶学习
本教程介绍了现代测试自动化中的两个强大框架:
-
Behave:用于清晰、可维护的接口自动化测试
-
Airtest:用于高效的移动端UI自动化测试
进阶学习资源:
-
Behave官方文档
-
Airtest官方文档
-
Poco框架GitHub
实际项目建议:
-
从简单场景开始,逐步增加复杂度
-
建立良好的测试数据管理策略
-
将自动化测试集成到CI/CD流程中
-
定期维护和更新测试用例
通过结合这两种框架,你可以构建覆盖接口和UI的全方位自动化测试解决方案,显著提高软件质量和发布速度。