我正在 django 中进行测试,并使用装饰器 mock.patch.object() 来模拟对象方法。我想在该类的另一个函数中使用相同的装饰器。为此,我将装饰器从函数移至类。这解决了我的问题,但现在我想添加另一个测试函数,它不应该模拟这些函数。
@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClass(testcases.TestCase):
def setUp(self):
# contains my setup that I want to use in all functions for this test class
def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2):
# I want to use those mocked functions here
def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2):
# I want to use those mocked functions here too
def test_function_3(self):
# I do not want to use those mocked functions here
如果我这样做,它会抛出一个错误:
TypeError: test_function_3() takes 1 positional argument but 3 were given
那么我应该做什么,以便我可以在所有函数中使用 setUp 并仅在两个函数中使用模拟函数?
PS:我只展示了 2 个模拟函数,但实际上我正在模拟 8 个函数,因此重复 mock.patch 可能不是一个好主意。
最佳答案
创建一个不带装饰器的父测试类 - TestParent
,其中包含 setUp
方法中的代码,然后在两个子类中继承该类 - 一个是经过装饰的,以及一个不是:
class TestClassParent(testcases.TestCase):
def setUp(self):
# contains my setup that I want to use in all functions for this test class
@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClassMocked(TestClassParent):
def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2):
# I want to use those mocked functions here
def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2):
# I want to use those mocked functions here too
class TestClassNotMocked(TestClassParent):
def test_function_3(self):
# I do not want to use those mocked functions here
这将允许您共享设置代码,并指定不应模拟哪些方法。
关于python - 如何在 python 中的多个函数上使用相同的装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60987251/