我正在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个功能,因此重复模拟.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
这将允许您共享安装代码,并指定不应模拟的方法。