在Python的pytest测试框架中,setup
和teardown
是用于准备测试环境和清理测试环境的钩子函数。不过,pytest中使用的术语略有不同。pytest使用setup_method
、teardown_method
、setup_class
、teardown_class
、setup_module
和teardown_module
等函数来执行不同级别的设置和清理任务。下面详细讲解这些函数:
1. 函数级别的设置和清理
setup_method(self, method)
: 在每个测试方法(函数)执行前调用。teardown_method(self, method)
: 在每个测试方法(函数)执行后调用。
这两个方法适用于测试类中的每个单独测试方法。
import pytest
class TestExample:
def setup_method(self, method):
# 在每个测试方法前执行
print("Setting up for", method.__name__)
def teardown_method(self, method):
# 在每个测试方法后执行
print("Tearing down after", method