在測試用例的前面加上:
@pytest.mark.parametrize("參數名", 列表數據) # (mark 譯:馬爾科、parametrize 譯:普軟木踹絲)
參數名:用來接收每一項數據,並作為測試用例的參數。
列表數據:一組測試數據,元祖、字典、列表。
方式一:
@pytest.mark.parametrize('參數名', [數據1, 數據2, 數據3......])
import pytest @pytest.mark.parametrize('demo', [1, 2, 3, 4]) def test_demo(demo): print(f'測試數據為:{demo}') assert demo in [0, 1, 2, 3, 4, 5]
執行結果:
方式二:
@pytest.mark.parametrize("參數1,參數2", [(數據1, 數據2), (數據1, 數據2)])
import pytest @pytest.mark.parametrize("a,b,c", [(1, 3, 4), (10, 35, 45), (22.22, 22.22, 44.44)]) def test_add(a, b, c): res = a + b print(f"測試數據為:{res}") assert res == c
執行結果:
方式三:(笛卡爾積)
- 組合參數化:多組參數,依次組合。
- 使用多個@pytest.mark.parametrize
import pytest @pytest.mark.parametrize('test1', [1, 2]) @pytest.mark.parametrize('test2', [3, 4]) def test_demo(test1, test2): print(f'測試數據為:{test1}和{test2}') assert (test1, test2) in [(1, 3), (1, 4), (2, 3), (2, 4), (5, 6)]
執行結果:
*******請大家尊重原創,如要轉載,請注明出處:轉載自:https://www.cnblogs.com/shouhu/,謝謝!!*******