使用 pytest 参数化进行单元测试

unit testing with pytest parametrize

我有以下测试代码:

class TestMyCode(unittest.TestCase):
    @pytest.mark.parametrize('item', [5,4,10])
    def test_valid_range(self, item):
        self.assertTrue(1 <= item <= 1000)

这不是我的真实测试,这只是一个最小的重现示例。

我只需要对根据相同代码检查的输入进行参数化。

出于某种原因,这不起作用,我总是得到:

 TypeError: test_valid_range() missing 1 required positional argument: 'item'

我该如何解决?

您不能在 unittest.TestCase methods 上使用 @pytest.mark.parametrize。 PyTest没有办法传入参数

就这样:

@pytest.mark.parametrize('item', [5,4,10])
def test_valid_range(item):
    self.assertTrue(1 <= item <= 1000)