我正在使用 TestCase 为我的 django 应用程序编写测试,并且希望能够将参数传递给父类的 setUp 方法,如下所示:
from django.test import TestCase
class ParentTestCase(TestCase):
def setUp(self, my_param):
super(ParentTestCase, self).setUp()
self.my_param = my_param
def test_something(self):
print('hello world!')
class ChildTestCase(ParentTestCase):
def setUp(self):
super(ChildTestCase, self).setUp(my_param='foobar')
def test_something(self):
super(ChildTestCase, self).test_something()
但是,我收到以下错误:
TypeError: setUp() takes exactly 2 arguments (1 given)
我知道这是因为只有 self 仍然被传递,并且我需要覆盖类 __init__
才能使其正常工作。我是 Python 新手,不知道如何实现这一点。如有任何帮助,我们将不胜感激!
最佳答案
测试运行程序将调用您的 ParentTestCase.setup,仅使用 self 作为参数。因此,您将为这种情况添加默认值,例如:
class ParentTestCase(TestCase):
def setUp(self, my_param=None):
if my_param is None:
# Do something different
else:
self.my_param = my_param
注意:请注意不要使用可变值作为默认值(有关更多详细信息,请参阅 "Least Astonishment" and the Mutable Default Argument)。
关于python - 将额外参数传递给测试用例设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26111833/