在您的代码中,@pytest.mark.parametrize("args", [1, 2]) 正在装饰 TestClass 类,而不是各个测试方法。这意味着 args 参数将传递给类中的每个测试方法,其值设置为 1 用于第一个测试方法运行,然后设置为 2 用于第二个测试方法运行。
如果你想以特定顺序执行测试方法,你可以使用 pytest.mark.run 装饰器来指定测试应该运行的顺序。例如:
import pytest
@pytest.mark.run(order=1)
def test_first(self, args):
print(args)
@pytest.mark.run(order=2)
def test_second(self, args):
print(args)
@pytest.mark.parametrize("args", [1, 2])
class TestClass:
def test_first(self, args):
test_first(args)
def test_second(self, args):
test_second(args)
在这段代码中,test_first 和 test_second 是单独的函数,用 pytest.mark.run 装饰器装饰以指定它们的执行顺序。 TestClass 类包含以所需顺序简单调用装饰测试函数的方法。
请注意,您还可以在 TestClass 类本身上使用 pytest.mark.run 装饰器来指定方法的运行顺序。例如:
import pytest
@pytest.mark.parametrize("args", [1, 2])
@pytest.mark.run(order=1)
class TestClass:
def test_first(self, args):
print(args)
@pytest.mark.parametrize("args", [1, 2])
@pytest.mark.run(order=2)
class TestClass:
def test_second(self, args):
print(args)
在此代码中,TestClass 类本身用pytest.mark.run 修饰以指定其方法的运行顺序。 test_first 和 test_second 方法将以指定的顺序为每个 args 值运行。