首页 > 解决方案 > Pytest 在测试类中参数化

问题描述

我有以下代码,我试图用一些测试数据生成测试。

class Test_ABC(BaseTestCase):
    testdata = [
                (7,  'Jan', 2018, 'Jul', 2018),
                (8,  'Jan', 2018, 'Aug', 2018),
                (18, 'Jan', 2017, 'Jun', 2018),
                (36, 'Jan', 2015, 'Dec', 2017),
                (48, 'Jan', 2014, 'Dec', 2017),
               ]

    @pytest.mark.parametrize("a, b, c, d", testdata)
    def test_abc(self, a, b, c, d):
        print (a, b, c, d)

来自 BaseTestCase 的狙击手:

@pytest.mark.usefixtures('init_browser')
class BaseTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(BaseTestCase, self).__init__(*args, **kwargs)

当我使用 pytest 执行此脚本时,出现以下错误:

TypeError: test_abc() missing 5 required positional arguments: 'a', 'b', 'c', 'd'
C:\Python3\lib\unittest\case.py:605: TypeError

如果我不在测试类“Test_ABC”中继承 BaseTestCase,这似乎可行。

知道我在测试用例或 BaseTestCase 中缺少什么吗?

标签: pytest

解决方案


您在 param 中没有足够的参数(如错误所述)。尝试这个:

@pytest.mark.parametrize("a, b, c, d, e", testdata)
def test_abc(self, a, b, c, d, e):
    print (a, b, c, d)  # without year

而且 pytest 也不会在具有__init__构造函数的类中寻求测试。删除它并替换unittest.TestCaseobject


推荐阅读