为什么setup无法执行pytest的前置条件,用setup_method就能够运行?
import pytest
class Testsetup():
def setup(self):
print("前置条件")
def test_01(self):
print("你好")
if __name__ == '__main__':
pytest.main(["-s"])


为什么setup无法执行pytest的前置条件,用setup_method就能够运行?
import pytest
class Testsetup():
def setup(self):
print("前置条件")
def test_01(self):
print("你好")
if __name__ == '__main__':
pytest.main(["-s"])


关注引自免费微信小程序:皆我百晓生
在pytest中,setup 和 setup_method 有着不同的作用和调用方式:
setup方法。如果要定义一个针对整个测试类执行的前置条件,你需要使用setup_class装饰器,并且方法名应为setup_class而不是setup。例如:import pytest
class TestSetup:
@classmethod
def setup_class(cls):
print("前置条件(针对整个类)")
def test_01(self):
print("你好")
setup_method是pytest提供的一种方法级的前置条件装饰器,它会在每个测试方法(以test_开头的方法)执行前被调用。你代码中的setup_method应该改为setup_method_self以正确装饰方法,并确保pytest能识别:import pytest
class TestSetup:
def setup_method(self, method):
print("前置条件(针对每个测试方法)")
def test_01(self):
print("你好")
当你运行pytest时,setup_method会按预期在每个测试方法之前执行并打印“前置条件”。
所以,如果你想在每个测试方法执行前设置前置条件,你应该使用setup_method或者更新后的setup_method_self(pytest6之后推荐使用setup)。而如果想在测试类初始化时执行一次操作,则应使用setup_class。