干货|app自动化之如何参数化用例
参数化是自动化测试的一种常用技巧,可以将测试代码中的某些输入使用参数来代替。以百度搜索功能为例,每次测试搜索场景,都需要测试不同的搜索内容,在这个过程里面,除了数据在变化,测试步骤都是重复的,这时就可以使用参数化的方式来解决测试数据变化,测试步骤不变的问题。
参数化就是把测试需要用到的参数写到数据集合里,让程序自动去这个集合里面取值,每条数据都生成一条对应的测试用例,直到集合里的值全部取完。
使用方法
使用 Appium 测试框架编写测试用例时,通常会结合 pytest 测试框架一起使用。使用 pytest 的参数化机制,可以减少代码重复,在测试代码前添加装饰器 @pytest.mark.parametrize,来完成数据的传输。示例代码如下:
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
运行结果如下:
from appium import webdriver
import pytest
from hamcrest import *
class TestXueqiu:
省略...
# 参数化
@pytest.mark.parametrize("keyword, stock_type, expect_price", [
('alibaba', 'BABA', 170),
('xiaomi', '01810', 8.5)
])
def test_search(self, keyword, stock_type, expect_price):
# 点击搜索
self.driver.find_element_by_id("home_search").click()
# 向搜索框中输入keyword
self.driver.find_element_by_id(
"com.xueqiu.android:id/search_input_text"
).send_keys(keyword)
# 点击搜索结果
self.driver.find_element_by_id("name").click()
# 获取价格
price = float(self.driver.find_element_by_xpath(
"//*[contains(@resource-id, 'stockCode')\
and @text='%s']/../../..\
//*[contains(@resource-id, 'current_price')]"
% stock_type
).text)
# 断言
assert_that(price, close_to(expect_price, expect_price * 0.1))
上面的代码,传入了两组测试数据,每组有三个数据分别为搜索关键词,股票类型,及股票价格。在执行测试用例时,分别将两组数据传入测试步骤中执行,对应搜索不同的关键词,使用 Hamcrest 来实现股票价格的断言。
app自动化测试(Android)参数化用例就讲完了,大家学会了么?我们下一期为大家讲解app自动化中Andriod WebView测试,有兴趣的小伙伴可以关注一下哦!
喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一键三连哦。更多技术文章