如何在Appium Python中避免每次测试后重启应用?
解决每次测试不重启App的方法
针对你的需求,核心思路是复用同一个Appium Driver实例,同时调整配置避免每次启动都重装/重置应用,具体步骤如下:
1. 调整Desired Capabilities
修改你的desired_cap,添加两个关键参数;如果App已经安装到测试设备上,还可以移除app路径参数(避免每次重新安装):
def goToDashboard(self): desired_cap = { "platformName": "Android", "platformVersion": "12", "deviceName": "Pixel 6", "appActivity": ".MainActivity", "appWaitActivity": ".MainActivity", "appPackage": "com.test.test", # 新增:不重置应用状态,保留缓存数据 "noReset": True, # 显式声明禁止完全重置(默认值为False,写出来更清晰) "fullReset": False, # 若App已安装到设备,可删除下方路径参数 # "app": "C:\\test\\test-app-release.apk", } driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_cap) bp = BasePage(driver) return driver
2. 复用Driver实例(以Pytest为例)
如果用Pytest作为测试框架,使用会话/模块级别的Fixture初始化一次Driver,让所有测试用例共用这个实例:
# 在conftest.py文件中定义Fixture import pytest from appium import webdriver from your_module import BasePage, Driver @pytest.fixture(scope="session") # session表示整个测试周期只初始化一次Driver def app_driver(): driver1 = Driver() driver = driver1.goToDashboard() yield driver # 所有测试完成后统一关闭Driver driver.quit() # 测试用例文件中直接调用Fixture def test_AddDevice(app_driver): bp = BasePage(app_driver) # 你的测试逻辑... def test_AnotherFeature(app_driver): bp = BasePage(app_driver) # 第二个测试直接复用已启动的App...
3. 测试后恢复初始页面
每次测试结束后,不要关闭App,而是回到应用首页,避免下一个测试受当前页面状态影响:
# 在BasePage类中添加回到首页的方法 class BasePage: def __init__(self, driver): self.driver = driver def back_to_home(self): # 方式1:调用Android返回键回到首页(需确保当前路径能返回至首页) self.driver.press_keycode(4) # 方式2:通过元素定位点击首页按钮(更稳定,需替换为你的首页元素ID) # self.driver.find_element(By.ID, "com.test.test:id/home_button").click() # 测试用例中调用恢复方法 def test_AddDevice(app_driver): bp = BasePage(app_driver) # 执行测试操作... bp.back_to_home() # 测试结束后回到首页
关键说明
noReset=True:会保留应用的缓存和状态,不会在每次启动时将应用重置到初始安装状态- Fixture的
scope参数:session表示所有测试文件共用一个Driver,module表示单个测试文件内共用,可根据你的测试场景选择 - 若需要重新安装App但不想每次重启,可添加
dontStopAppOnReset=True参数(需配合noReset使用,具体兼容性看Appium版本)
内容的提问来源于stack exchange,提问作者Dr. Agos
相关产品推荐
相关产品推荐

