向测试用例设置传递额外的参数

2024-10-02 14:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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()

但是,我得到了以下错误:

^{pr2}$

我知道这是因为只有self仍然被传递,我需要重写到类__init__才能使其工作。我是Python的新手,不知道如何实现它。感谢任何帮助!在


Tags: djangotestself应用程序parammydefsetup
1条回答
网友
1楼 · 发布于 2024-10-02 14:19:11

测试运行人员将调用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)。在

相关问题 更多 >