1

我正在使用 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 的新手,不知道如何实现这一点。任何帮助表示赞赏!

4

1 回答 1

1

测试运行器将调用您的 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”和可变默认参数)。

于 2014-09-30T05:38:10.003 回答