使用@pytest.mark.parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)
对测试进行参数化
1、常用参数:
argnames:参数名
argvalues:参数对应值,类型必须为list
当参数为一个时格式:[value]
当参数个数大于一个时,格式为:[(param_value1,param_value2.....),(param_value1,param_value2.....)]
参数值为N个,测试方法就会运行N次
2、作用范围设置:
参数化某个函数:
在测试函数上加@pytest.mark.parametrize()
# -*- coding: utf-8 -*-
import pytest
from operator import add
class TestAdd():
@pytest.mark.parametrize("test_input1,test_input2,expected1", [(3, 5, 8),(2, 4, 6),(6, 9, 42)])
def test_test07(self, test_input1, test_input2, expected1):
result = add(test_input1, test_input2)
assert result == expected1
运行命令:
pytest -v .\test_case_demo_pytest.py::TestAdd::test_test07
运行结果:
对类下的所有函数参数化:
在测试类上加@pytest.mark.parametrize(),类下的所有测试函数均可使用参数获得值
# -*- coding: utf-8 -*-
import pytest
from operator import add
@pytest.mark.parametrize("test_input1,test_input2,expected1", [(3, 5, 8),(2, 4, 6),(6, 9, 42)])
class TestAdd():
def test_test07(self, test_input1, test_input2, expected1):
result = add(test_input1, test_input2)
assert result == expected1
def test_test08(self, test_input1, test_input2, expected1):
result = add(test_input1, test_input2)
assert result == expected1
运行命令:
pytest -v .\test_case_demo_pytest.py::TestAdd
运行结果: